Learner
Learner

Reputation: 1523

Using fields/variable in Factory class to be used across objects created through factory

I am using Factory to create my objects like following, here both MyObject and YourObject classes implements MyInterface:

public class MyFactory {
    public static MyInterface myObject(int value, int commonValue) {
        return new MyObject(value, commonValue);
    }

    public static MyInterface yourObject(String str, int commonValue) {
        return new YourObject(str, commonValue);
    }
}

I want to set commonValue at the factory level instead of passing them as parameters in individual methods, as the same value is passed to create set of objects using factory. Also once I create one set of objects using the factory I want to reset commonValue to its default so that previously set value is not used by default later on. What is the right way to do this?

Upvotes: 0

Views: 1971

Answers (2)

assylias
assylias

Reputation: 328775

Since your commonValue can change, a cleaner way (IMHO) would be:

public class MyFactory {
    private final int commonValue;
    public MyFactory (int commonValue) { this.commonValue = commonValue; }

    public MyInterface myObject(int value) {
        return new MyObject(value, commonValue);
    }

    public MyInterface yourObject(String str) {
        return new YourObject(str, commonValue);
    }
}

And when you need to reset it, just create a new factory.

The benefits are:

  • it is clear what the value is (if you used a mutable value with a setter, some code could affect non related code)
  • it is thread safe

Upvotes: 4

Thom
Thom

Reputation: 15092

I use the Spring framework to do exactly that kind of thing. Let's me set up my factories up front and then construct from them. Is this an option?

Upvotes: -1

Related Questions