In the book "Java and Patterns" of Dr. Shanhong, this describes the construction (builder) Pattern:
Construction mode is the creation mode of the object. The construction mode separates the internal representation of a product (internal representation) from the production process of the product, allowing a construction process to produce objects with different internal representations.
Internal representation of the product
A product often has different components as part of the product, which may or may not be objects, and they are often called internal representations of the product (internal representation). Different products can have different internal appearances, that is, different parts. Using the build mode allows the client to not know what parts of the product are being generated, how the corresponding parts of each product are different from each other, how they are built, and how the products are formed.
construction of Object Nature
In some cases, an object can have some important properties, and the object cannot be used as a complete product until they have the proper value. For example, an e-mail message has a sender address, a recipient address, a subject, a content, an appendix, and so on, and the e-mail message cannot be sent until the minimum recipient address is assigned.
In some cases, some properties of an object must be assigned in a certain order to make sense. Another property cannot be assigned to a property until it is assigned a value. These conditions make the construction of nature itself related to complex business logic. At this time, this object is equivalent to a product to be built, and the object of these properties is equivalent to the parts of the product, the process of building the product is the process of building parts. Because the process of building the parts is complex, the construction of these parts is often "externally" to another object called the builder, and the object returned to the client is a product object where all the parts have been built.
The construction model uses a Director object and a concrete builder object to build all the parts, creating a complete product object. The builder model hides the structure of the product and the construction of the parts of the product, separating the responsibility for directing the construction process from the responsibility of the concrete builder's parts, and achieving the purpose of dividing and encapsulating the responsibilities.
Structure of the construction mode
In this schematic system, the final product products have only two parts, namely Part1 and Part2. The corresponding construction methods are also two: BuildPart1 () and BuildPart2 (), and it can be seen that this pattern involves four roles, namely:
Abstract Builder role: An abstract interface is given to standardize the construction of each component of the Product object. Typically, this interface is independent of the application's business logic. The direct creation of the Product object in the schema is the Concrete Builder (concretebuilder) role. The concrete builder class must implement two methods required by this interface: one is the construction method (BuildPart1 and BuildPart2) and the other is the return structure method (Retrieveresult). In general, the number of parts contained in the product corresponds to the number of construction methods. In other words, how many parts there are, how many corresponding construction methods.
Concrete Builder (concretebuilder) role: This role is a class that is closely related to the application, which creates an instance of the product under the application invocation. The tasks to be accomplished by this role include: 1. Implement the interface declared by the abstract Builder builder, and give a step-by-step procedure for creating a product instance. 2. After the completion of the construction process, provide an example of the product.
Director role: The class that holds the role invokes the concrete builder role to create the Product object. It should be noted that the Director's role does not have the specific knowledge of the product class, the real knowledge of the product class is the specific builder role.
Product role: A product is a complex object in construction. In general, there will be more than one product class in a system, and these product classes do not necessarily have a common interface and can be completely unrelated.
The Director role is the role of dealing with clients. The director divides the client's request to create a product into a build request for each part, and then delegates the request to the specific builder role. The concrete builder's role is to do concrete construction work, but it is not known to the client.
In general, there is a corresponding concrete builder class for each product class. These products should have the same number of parts, and each one has a construction method corresponding to all the builders ' roles.
Source
Product Category Products
public class Product {
/**
* Define some operations on the product
*/
Private String part1;
Private String Part2;
Public String GetPart1 () {
return part1;
}
public void SetPart1 (String part1) {
This.part1 = Part1;
}
Public String GetPart2 () {
return part2;
}
public void SetPart2 (String part2) {
This.part2 = Part2;
}
}
Abstract Builder Class Builder
Public interface Builder {
public void BuildPart1 ();
public void BuildPart2 ();
Public Product Retrieveresult ();
}
Concrete Builders ' class ConcreteBuilder
public class ConcreteBuilder implements Builder {
Private Product Product = new product ();
/**
* Product Parts Construction Method 1
*/
@Override
public void BuildPart1 () {
Building the first part of a product
Product.setpart1 ("No.: 9527");
}
/**
* Product Parts Construction Method 2
*/
@Override
public void BuildPart2 () {
Building a second part of a product
Product.setpart2 ("Name: XXX");
}
/**
* Product Return method
*/
@Override
Public Product Retrieveresult () {
return product;
}
}
Director's class Director
public class Director {
/**
* Hold the Builder object you currently need to use
*/
Private builder Builder;
/**
* Construction method, incoming builder object
* @param Builders Builder Object
*/
Public Director (Builder builder) {
This.builder = Builder;
}
/**
* Product Construction method, responsible for invoking each part construction method
*/
public void construct () {
Builder.buildpart1 ();
Builder.buildpart2 ();
}
}
Client class Clients
public class Client {
public static void Main (String[]args) {
Builder builder = new ConcreteBuilder ();
Director Director = new Director (builder);
Director.construct ();
Product Product = Builder.retrieveresult ();
System.out.println (Product.getpart1 ());
System.out.println (Product.getpart2 ());
}
}
Timing Diagram
The client is responsible for creating the director and the Concrete builder object. The client then gives the specific builder object to the director, who operates the concrete builder and begins to create the product. When the product is finished, the builder returns the product to the client.
The task of creating a concrete builder object to the client rather than the Director object is to make the coupling of the Director object and the Concrete builder object dynamic, so that the Director object can manipulate any one of several concrete builder objects.
Usage Scenarios
Suppose there is an electronic magazine system that periodically sends e-magazines to users ' e-mail boxes. Users can subscribe to e-Magazines via web pages or end their subscriptions via web pages. When a customer starts a subscription, the system sends an email greeting, and when the customer ends the subscription, the system sends an e-mail message saying farewell. This example is the system responsible for sending "welcome" and "Farewell" Mail module.
In this case, the product class is a "welcome" and "Farewell" message sent to a customer, as shown in.
Although in this example each product class has a common interface, but this is only unique to this example, does not represent the characteristics of the construction model. The build mode can be applied to product classes with completely different interfaces. In most cases, it is not known what the final product will be, so in the standard construction mode, it is generally not necessary to define abstract interfaces to the product, because the resulting product varies widely and it is almost meaningless to define a public interface for these products.
Shown is the class diagram for this system.
The system includes the client, the director, the Abstract Builder (builder), the concrete builders (Welcomebuilder and Goodbyebuilder), Products (Welcomemessage and goodbyemessage) and other roles.
Source
Abstract class Automessage source code, the Send () operation is only indicative, and does not give any code to send e-mail.
Public abstract class Automessage {
Recipient address
Private String to;
Sender Address
Private String from;
Title
Private String subject;
Content
Private String body;
Send Date
Private Date senddate;
public void Send () {
SYSTEM.OUT.PRINTLN ("Recipient address:" + to);
System.out.println ("Sender Address:" + from);
System.out.println ("title:" + subject);
System.out.println ("content:" + body);
SYSTEM.OUT.PRINTLN ("Send date:" + senddate);
}
Public String Getto () {
return to;
}
public void Setto (String to) {
This.to = to;
}
Public String Getfrom () {
return from;
}
public void Setfrom (String from) {
This.from = from;
}
Public String Getsubject () {
return subject;
}
public void Setsubject (String subject) {
This.subject = subject;
}
Public String GetBody () {
return body;
}
public void Setbody (String body) {
This.body = body;
}
Public Date getsenddate () {
return senddate;
}
public void Setsenddate (Date senddate) {
This.senddate = senddate;
}
}
Specific Product class Welcomemessage
public class Welcomemessage extends Automessage {
/**
* Construction Sub
*/
Public Welcomemessage () {
SYSTEM.OUT.PRINTLN ("Send welcome message");
}
}
Specific Product class Goodbyemessage
public class Goodbyemessage extends automessage{
/**
* Construction Sub
*/
Public Goodbyemessage () {
System.out.println ("Send Farewell Message");
}
}
Abstract Builder Class
Public abstract class Builder {
protected Automessage msg;
How to build a title part
public abstract void Buildsubject ();
How to build content parts
public abstract void Buildbody ();
How to Build recipient parts
public void Buildto (String to) {
Msg.setto (to);
}
How to build a sender part
public void Buildfrom (String from) {
Msg.setfrom (from);
}
Method of construction of sending time parts
public void Buildsenddate () {
Msg.setsenddate (New Date ());
}
/**
* After the mail product is finished, use this method to send mail
* This method is equivalent to the product return method
*/
public void SendMessage () {
Msg.send ();
}
}
Concrete Builder Welcomebuilder
public class Welcomebuilder extends Builder {
Public Welcomebuilder () {
msg = new Welcomemessage ();
}
@Override
public void Buildbody () {
TODO auto-generated Method Stub
Msg.setbody ("Welcome content");
}
@Override
public void Buildsubject () {
TODO auto-generated Method Stub
Msg.setsubject ("Welcome title");
}
}
Concrete Builder Goodbyebuilder
public class Goodbyebuilder extends Builder {
Public Goodbyebuilder () {
msg = new Goodbyemessage ();
}
@Override
public void Buildbody () {
TODO auto-generated Method Stub
Msg.setbody ("Farewell content");
}
@Override
public void Buildsubject () {
TODO auto-generated Method Stub
Msg.setsubject ("farewell title");
}
}
Director of Directors, this class provides a construct () method that invokes the builder's construction method, including Buildto (), Buildfrom (), Buildsubject (), Buildbody (), Buildsenddate () and so on, so that a part of the product objects are built, both automessage objects.
public class Director {
Builder Builder;
/**
* Construction Sub
*/
Public Director (Builder builder) {
This.builder = Builder;
}
/**
* Product Construction method, responsible for invoking the construction method of each part
*/
public void construct (string toaddress, String fromaddress) {
This.builder.buildTo (toaddress);
This.builder.buildFrom (fromaddress);
This.builder.buildSubject ();
This.builder.buildBody ();
This.builder.buildSendDate ();
This.builder.sendMessage ();
}
}
Client clients
public class Client {
public static void Main (string[] args) {
TODO auto-generated Method Stub
Builder builder = new Welcomebuilder ();
Director Director = new Director (builder);
Director.construct ("[Email protected]", "[email protected]");
}
}
The construction pattern is divided into two important parts:
1. A part is the builder interface, here is the definition of how to build the individual parts, that is, how each part function is realized, and how to assemble the parts into the product;
2. Another part is that Director,director is aware of how to assemble a product, which means that the Director is responsible for the overall build algorithm and is usually executed in a step-by.
No matter how it changes, there are two parts in the construction mode, one part is the component construction and the product assembly, the other part is the overall built algorithm . It is important to recognize this because in the construction model, the emphasis is on fixing the overall built algorithm, while flexibly extending and switching the specific construction of the part and the way the product is assembled.
To put it bluntly, the focus of the construction model is to separate the construction algorithm and the concrete construction implementation, so that the construction algorithm can be reused. The concrete construction implementation can be easily extended and switched, which can be flexibly combined to construct different product objects.
Building complex objects using build mode
Consider such a practical application, to create an insurance contract object, many of the attributes of the values are constrained, the object is created to meet the constraints of these rules. Constraint rules such as: insurance contracts can usually be signed with individuals, or a company can be signed, but an insurance contract can not be signed with both individuals and companies. There are many such constraints in this object, and building a complex object using a build pattern usually simplifies the construction pattern because the goal is to create a complex object, so simplifying the program will make it more concise. The approximate simplification is as follows:
Because the builder mode is used to create an object, there is no need to define a builder interface, directly providing a concrete builder class.
For creating a complex object, there may be many different choices and steps, altogether removing the "director", combining the function of the Director with the function of the client, that is, the client this time is equivalent to the Director, it to guide the builder class to build the complex objects needed.
Insurance Contract Category
/**
* Insurance Contract Object
*/
public class Insurancecontract {
Insurance Contract Number
Private String Contractid;
/**
* The name of the insured person, the same insurance contract, either signed with the personnel, or signed with the company
* That is to say, the "insured" and "by the insurance companies" These two attributes, cannot have the value at the same time
*/
Private String personname;
By the name of the insurance company
Private String CompanyName;
Insurance Commencement Date
Private long begindate;
The expiry date of the insurance will be greater than the commencement date of the insurance
Private long endDate;
Other data
Private String Otherdata;
Private construction methods
Private Insurancecontract (ConcreteBuilder builder) {
This.contractid = Builder.contractid;
This.personname = Builder.personname;
This.companyname = Builder.companyname;
This.begindate = builder.begindate;
This.enddate = builder.enddate;
This.otherdata = Builder.otherdata;
}
/**
* Some operations of the insurance contract
*/
public void Someoperation () {
System.out.println ("The current operating insurance contract number is" "+this.contractid+" "");
}
public static Class concretebuilder{
Private String Contractid;
Private String personname;
Private String CompanyName;
Private long begindate;
Private long endDate;
Private String Otherdata;
/**
* Construct method, pass in required parameter
* @param Contractid Insurance Contract number
* @param begindate Insurance Contract Commencement date
* @param endDate Insurance Contract Expiry date
*/
Public ConcreteBuilder (String contractid,long begindate,long endDate) {
This.contractid = Contractid;
This.begindate = begindate;
This.enddate = endDate;
}
Name of the insured member
Public ConcreteBuilder setpersonname (String personname) {
This.personname = PersonName;
return this;
}
By the name of the insurance company
Public ConcreteBuilder setcompanyname (String companyName) {
This.companyname = CompanyName;
return this;
}
Other data
Public ConcreteBuilder Setotherdata (String otherdata) {
This.otherdata = Otherdata;
return this;
}
/**
* Build a real object and return
* @return Insurance Contract object to be constructed
*/
Public Insurancecontract Build () {
if (Contractid = = NULL | | Contractid.trim (). Length () ==0) {
throw new IllegalArgumentException ("The contract number cannot be empty");
}
Boolean Signperson = (personname! = null && Personname.trim (). Length () > 0);
Boolean signcompany = (CompanyName! = null && Companyname.trim (). Length () > 0);
if (Signperson && signcompany) {
throw new IllegalArgumentException ("an insurance contract cannot be signed with both the individual and the Company");
}
if (Signperson = = False && Signcompany = = False) {
throw new IllegalArgumentException ("an insurance contract cannot be executed without an object");
}
if (begindate <= 0) {
throw new IllegalArgumentException ("an insurance contract must have a date of commencement");
}
if (EndDate <=0) {
throw new IllegalArgumentException ("an insurance contract must have a date of expiry");
}
if (EndDate < begindate) {
throw new IllegalArgumentException ("The expiry date of an insurance contract must be greater than the effective Date");
}
return new Insurancecontract (this);
}
}
}
Client class
public class Client {
public static void Main (String[]args) {
Creating builder Objects
Insurancecontract.concretebuilder Builder =
New Insurancecontract.concretebuilder ("9527", 123L, 456L);
Set up the required data and then build the insurance contract object
Builder.setpersonname ("Xiao Ming"). Setotherdata ("Test"). Build ();
Methods of operating insurance contract objects
Contract.someoperation ();
}
}
In this example, the concrete builder is merged into the Product object, and the constructor of the product object is privatized to prevent the client from using the builder to build the product object, instead of directly using new to build the Product object. In addition, the function of this builder is to create the object that is being built, completely without a separate class.
Under what circumstances to use construction mode
1. The product objects that need to be generated have complex internal structures, each of which can itself be an object or simply an integral part of an object (that is, a product object).
2. The properties of the product objects that need to be generated depend on each other. The construction mode can enforce a step-through construction process, so if one property of a Product object has to be assigned after another attribute is assigned, using the build mode is a good idea.
3. Some other objects in the system are used during object creation, which are not readily available during the creation of the Product object.
The construction model of Java and pattern