Quick actions

cmd+k|ctrl+k

Navigation

Languages

Builder pattern subclassing - solved? Without traits

Snippet info

Language

Java

Visibility

public

Author

rich.north

Created

2016-04-24T12:24:26Z

Updated

2016-04-24T12:24:26Z

class Base<SUB> {

    public SUB withBaseParam(String param) {
        System.out.println("Here in Base with " + param);
        return (SUB) this;
    }

    public Base build() {
        System.out.println("Building in Base class");
        return this;
    }
}

class Subclass extends Base<Subclass> {

    public Subclass withSubclassParam(String param) {
        System.out.println("Here in Subclass with " + param);
        return this;
    }
}

class AnotherSubclass extends Base<AnotherSubclass> {

    public AnotherSubclass withAnotherSubclassParam(String param) {
        System.out.println("Here in AnotherSubclass with " + param);
        return this;
    }
}

public class Client {
    public static void main(String[] args) {

        System.out.println("Subclass example:\n");
        new Subclass()
                .withSubclassParam("s1")
                .withBaseParam("foo")
                .withSubclassParam("s2")
                .withSubclassParam("s3")
                .build();


        System.out.println("\n\nAnotherSubclass example:\n");
        new AnotherSubclass()
                .withBaseParam("foo")
                .withAnotherSubclassParam("s1")
                .withBaseParam("bar")
                .withAnotherSubclassParam("s2")
                .withAnotherSubclassParam("s3")
                .withBaseParam("baz")
                .build();
    }
}
INFO