Builder
Defined
Building complex objects from simple objects step-by-step
Where to use and benefits
A complex object can be made only by clarifying the type and content. The completed object is separated from the details of the creation of it.
The process of creating a complex object is decoupled from the components it contains.
Separates the code that is created and expressed.
Programmers have better control over the process of creating.
Related modes include:
Abstract factory model, it is mainly concentrated on the level of the factory model, perhaps simple, perhaps complex. A builder model is mainly used to build complex objects based on simple objects.
Composite mode, which is used primarily to create complex objects.
Example
such as building a house, we need so many steps:
1 Laying the groundwork
2 Building Framework
3 Building Outdoor
4 Building Indoor
Let's use an abstract class housebuilder to define these four steps. Subclasses of any housebuilder class will follow these four steps to build the house (that is, implement the four methods in subclasses). Then we use a workshop class to enforce these four-step sequences (that is, we have to do it in the first three steps in order to build the room). The Testbuilder class will be used to test the compatibility between these classes and to examine the building process.
import java.util.*;
class WorkShop {
//force the order of building process
public void construct(HouseBuilder hb) {
hb.buildFoundation();
hb.buildFrame();
hb.buildExterior();
hb.buildInterior();
}
}