質問

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?

役に立ちましたか?

解決

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

他のヒント

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?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top