Question

I need to build objects of a class which has 3 fields: A, B and C. A valid object has at least one of A, B or C set by the user. I looked into the Builder Pattern, which is close to what I want, but only 1 field is made mandatory. I want that 1 field which must be set to be any one of the 3 that I have. Any suggestions?

My alternative is to use 7 constructors (for {A}, {B}, {C}, {A,B}, {B,C}, {A,C}, {A,B,C})

Était-ce utile?

La solution

You can use a builder for that. Short example with only two fields instead of three:

public final class MyBuilder
{
    private X a, b;

    public MyBuilder withA(X a)
    {
        b = null;
        this.a = a;
        return this;
    }

    public MyBuilder withB(X b)
    {
        a = null;
        this.b = b;
        return this;
    }

    public MyClass build()
    {
        if (a == null && b == null)
            barf(); // <-- throw exception here
        // A and B inherit MyClass
        return a != null ? new A(a) : new B(b);
    }
}

Autres conseils

You can force A, B, or C to be passed in the build() method:

class ValidBuilder {
  public ValidBuilder withA(Object a) {}
  public ValidBuilder withB(Object b) {}
  public ValidBuilder withC(Object c) {}

  public ValidObject buildA(Object a) { }
  public ValidObject buildB(Object b) { }
  public ValidObject buildC(Object c) { }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top