Builder pattern

Builder allows to create a complex object step by step.

problems

Let object has a lot properties that must be initialized. If we will use single constructor it will be look ugly. If we create an object and set its properties later, then there will be the possibility of using a partially initialized object.

advantages

  1. More pretty code.
  2. Have better control over the creation process.
 public class Demo{
    private int prop1;
    // ...
    private int propN;

    // if necessary
	// disallow to create the object by constructor 
    // outside from the class
    private Demo(){
    
    }

    public static class Builder(){
        private Demo obj = new Demo();
		
        public Builder setProp1(int v){
            obj.prop1=v;
            return this;
        }
        // ...
        
        public Builder setPropN(int v){
            obj.propN=v;
            return this;
        }
        
        private void check(){
            if(!some_cond){
                 throw new IllegaStateException("something was wrong");
            }
            // ...
        }
        
        // return a fully initialized object to the client
        public Demo build(){
            check();
            return obj;
        }
    }
}

// using
Demo demo = new Demo.Builder()
                .setProp1(arg1)
                // ...
                .setPropN(argN)
                .build();

Demo.Builder builder = new Demo.Builder();
if(some_cond){
    builder.setProp1(arg1);
}
// ...
builder.setPropN(argN);

Demo demo1 = builder.build();