Multiple optional arguments in constructor in Java - exponential number of constructors

亡梦爱人 提交于 2019-12-10 23:57:55

问题


This is something I've encountered a few times and haven't been able to find a satisfying answer yet. This seems pretty stupid, but after googling this for a while I couldn't come up with something good.

Let's say I have a class with 20 instance variables, each of which is optional (will be initialized or not).

Now I want my constructor(s) to handle all the cases, in case of a few instance variables it's fine and I can just create constructors with different signatures, but here I have 20, so I would need 2^20=1,048,576 constructors to handle all the cases ! That seems ... not very optimal, don't you agree?

So since with this brute force approach I basically have to construct 2^n constructors, where n is the number of instance variables, I want to find a better way to do it.

I've seen a couple solutions for this problem, but I believe they all on assumptions on the data, but in my case each of these variables can be initialized or not at random, I have no way of knowing that before initialization.

I'm looking for some design patterns or ideas that I could apply to make my code a bit more ... maintainable (no don't worry I didn't create 1M+ constructors :)

Thanks.


回答1:


Try the Builder pattern:

http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html




回答2:


Combine the Bean pattern with a Builder. YourObject will not have inconsistent state halfway through its construction, but it will still take 20+ set operations and you can make YourObject immutable (if you want) - but not YourObjectBuilder.

public class YourObject {
    private Type field1;
    private Type field2;
    private Type field3;
    ...
    YourObject ( Type field1 , Type field2 , Type field3 ... ) { }
}

public class YourObjectBuilder {
    private Type field1;
    private Type field2;
    private Type field3;
    ...

    public YourObjectBuilder() {
    }

    public YourObject make ( ) {
         return new YourObject ( field1 , field2 , field3 ... ) ;
    }

    public void setField1(Type t) {
        field1 = t;
    }

   public void setField2(Type t) {
        field2 = t;
   }

    public void setField3(Type t) {
        field3 = t;
    }
    ...
}



回答3:


public class YourObject {
    private Type field1;
    private Type field2;
    private Type field3;
    ...

    public YourObject() {
    }

    public void setField1(Type t) {
        field1 = t;
    }

   public void setField2(Type t) {
        field2 = t;
   }

    public void setField3(Type t) {
        field3 = t;
    }
    ...
}


来源:https://stackoverflow.com/questions/10158970/multiple-optional-arguments-in-constructor-in-java-exponential-number-of-const

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!