Builder pattern is an object creation design pattern, after the ealier one – Singleton. This pattern allows the client side create a complex object by specifing only its type and its content. In fact, we see builder pattern in something likes that:
When to use this pattern? A programmer will want to use builder pattern when:
- He want to replace the Telescoping Constructor Pattern. This happens when he works with a class contains too many attributes, he has to create many constructors with increasing number of parameters.
- He need create a complex object that the algorithm for creating this object should be independent of the parts make up it.
How to implement? By default, a common implementation of the Builder pattern has four component:
- The Builder defines an abstract class to create parts of Product object.
- The ConcreateBuilder implements the abstract class to constructor and put parts toghether. It defines and keep track of representation it creates. And also provides interfaces for retrieving created products.
- The Product represents complex object will be used.
- The Director initalizes object that creates Builder object.
Let’s take a look at this sample for more informations. The sample here creates rooms for a hourse throught a common interface builder. Here is our abstract class Builder. It provides an interface to add/remove room’s window, then return this room to us. The function at line 5th will add or remove room’s window, the line 7th allows us to retrieve the result.
And this is our ConcreateBuilder, BedRoomBuilder. It contains a BedRoom attribute that represent the product.
Finally, Director use the builder to create appropriate room.
Builder pattern with inheritance and generic. Sometime we need an abstract builder class for specifing common step-by-step to create our product, and subclass-builder will override these funtions or add neccessary others. Well, it’s time for self-bounding generics.
Now, the abstract builder class is implemented like:
Function selft() at line 14th will return appropriate instance of Builder in subclass.
In subclass BedRoomBuilder:
You can find full source here.