When using the Builder template, why not use the builder object to access the configuration of the object?

when using the Builder template, why shouldn't I reuse the constructor object to access the configuration of the object? For instance:

The usual way:

ObjectA(ObjectBuilder b) { this.a = b.getA(); } public Object getA(){ return this.a; } 

But why can't I just use this:

 ObjectA(ObjectBuilder b) { this.builder = b; } public Object getA(){ return this.builder.getA(); } 

Thanks:)

+5
source share
1 answer

The main reason for using the builder is to create an immutable object: the builder is changed, what it creates is not (required).

If you delegate to the builder, your instance will be changed again: anyone who has a reference to the same instance of ObjectBuilder can modify your ObjectA . This means that any checks you perform against the validity of the ObjectA state at build time can be invalidated.

If you need a mutable object, there is no need for a linker: just set it to ObjectA .

+7
source

All Articles