Monday, April 2, 2007

Builder

What can we do when creating a complex object that consists of lots of small logic/semantic units? The separability of semantic and implementation is required to ensure later maintainance of code. Abstract Factory helps in this way. But as for a complex object, different directors are usually needed to create different versions. Hence it's better separate the directions and basic unit-creating interfaces. After the buiding procedure carried out by directors, the object can be handed to later applications.
Create a builder interface for creating basic units. It might not be a totally abstract class. Its subclasses implements different styles of units. It maintains the object to be built, however without directions, thus it can't build the desired object itself.
Get a director that contains a builder. It maintains the object to be built by delegating all basic building operations to the builder. Its subclasses or itself implement the semantic direction of weaving all units together.
The following picture shows how the two parts interacts with each other:

What's the difference between Abstract Factory and a builder? Well, an Abstract Factory does not maintain a complex objects to be built. In fact, it only provides a unified interface of creating objects of different styles. The Builder, more than providing different styles by subclasses, maintains a complex object, which means a Builder is aimed at building something and the semantic building is delegated to a director which commands the builder do what it wishes to.

Then it has the following cons and pros:
  • It separates different styles of implementation from the semantic weaving.
  • Usually, we have to provide a default building result for the top Builder (the interface).

No comments: