0

I can't quite comprehend how to best go about implementing a Builder pattern for the following generics hierarchy.

Base class,

@lombok.Data
public class Node<T> {

    private T data;
    private String source;
}

Child class,

@lombok.Data
public class MyNode extends Node<MyNode> {
    private String firstDummy;
    private String secondDummy;
}

Is there anyway to apply an anonymous builder class to the parent and extend it in the child class ?

Updated

If i have an anonymous builder like so for the Parent,

public class Node<T> {

    private T data;
    private final String source;

    public static abstract class Builder<S extends Node> {

        private String source;

        public Builder<S> withSource(String source) {
            this.source = source;
            return this;
        }

        public abstract S build();
    }

    public static Builder<?> builder() {
        return new Builder<Node>() {
            @Override
            public Node build() {
                return new Node(this);
            }
        };
    }

    protected Node(Builder<?> builder) {
        this.source = builder.source;
    }
}

How do I then implement the builder for T in Node class ?

nixgadget
  • 6,983
  • 16
  • 70
  • 103

1 Answers1

0

If you want to practice im implementing builders, then yes, you can implement them. The hint of @nixgadget is good.

But if you just need a builder, add an annotation @Builder and Lombok will do that for you.

mentallurg
  • 4,967
  • 5
  • 28
  • 36