All posts by tarry

Builder Design Pattern and Inheritance

Builder Design Pattern and Inheritance

public class CarBuilder {
    private double windows;
    CarBuilder addWindows(){
        System.<em>out</em>.println("Adding Windows");
        return this;
    };
    CarBuilder addColor(){
        System.<em>out</em>.println("Adding Colors");
        return this;
    };
    protected CarBuilder(Builder&lt;?> builder) {

        System.<em>out</em>.println("carBuilder(builder)");
        this.windows = builder.windows;
    }
public static abstract class Builder&lt;T extends Builder&lt;T>> {
    private double windows;

    protected abstract T self();

    public T windows(double windows) {
        this.windows = windows;
        return self();
    }

    public CarBuilder build() {
        return new CarBuilder(this);
    }
}

    private static class Builder2 extends Builder&lt;Builder2> {
        @Override
        protected Builder2 self() {
            return this;
        }
    }

    public static Builder&lt;?> builder() {
        return new Builder2();
    }
}

public class SuVBuilder extends CarBuilder  {
    private double wheel;

    CarBuilder addWheels(){
        System.<em>out</em>.println("Adding wheels");
        return this;
    }

    public static abstract class Builder&lt;T extends Builder&lt;T>> extends CarBuilder.Builder&lt;T> {
        private double wheel;

        public T wheel(double wheel) {
            this.wheel = wheel;
            return self();
        }

        public SuVBuilder build() {
            return new SuVBuilder(this);
        }
    }

    private static class Builder2 extends Builder&lt;Builder2> {
        @Override
        protected Builder2 self() {
            return this;
        }
    }

    public static Builder&lt;?> builder() {
        return new Builder2();
    }

    protected SuVBuilder(Builder&lt;?> builder) {
        super(builder);
        System.<em>out</em>.println("SuvBuilder");
        this.wheel = builder.wheel;
    }
}
public class Main {

    public static void main (String[] args)
    {
        CarBuilder cb;
        final SuVBuilder s =  SuVBuilder.<em>builder</em>().windows(1.0).build();
        final CarBuilder s1 =  CarBuilder.<em>builder</em>().windows(1.0).build();
        System.<em>out</em>.println( s );
        long count=0;
        
    }
}

REFERENCE: https://www.sitepoint.com/self-types-with-javas-generics/

Advantage/Features of discussed BUilder Pattern:

a. No need of re decleration of data members again in child classses.

b. Generics used to identify and seperate child objects from parent objects.

c. Self types with java generics

d. Implementing builder pattern along inherited classes.