Home
Builder Pattern
Intent
- Defines an instance for creating an object but letting subclasses decide which class to instantiate
- Refers to the newly created object through a common interface
Implementation
The Builder design pattern uses the Factory Builder pattern to decide which concrete class to initiate in order to build the desired type of object, as we will see below in the UML diagram:
The participants classes in this pattern are:
- The Builder class specifies an abstract interface for creating parts of a Product object.
- The ConcreteBuilder constructs and puts together parts of the product by implementing the Builder interface. It defines and keeps track of the representation it creates and provides an interface for saving the product.
- The Director class constructs the complex object using the Builder interface.
- The Product represents the complex object that is being built.
The client, that may be either another object or the actual client that calls the main() method of the application, initiates the Builder and Director class. The Builder represents the complex object that needs to be built in terms of simpler objects and types. The constructor in the Director class receives a Builder object as a parameter from the Client and is responsible for calling the appropriate methods of the Builder class. In order to provide the Client with an interface for all concrete Builders, the Builder class should be an abstract one. This way you can add new types of complex objects by only defining the structure and reusing the logic for the actual construction process. The Client is the only one that needs to know about the new types, the Director needing to know which methods of the Builder to call.
No comments:
Post a Comment