The build mode is the object creation mode. The construction model can separate the internal representation of a product (internal representation) from the production process of the product, so that a building process can generate product objects with different internal representations.
Internal appearance of the product
A product usually has different components as parts of the product. These parts may be objects or not objects. They are also called internal representation ). Different products can have different internal representations, that is, different parts. Using the construction mode, the client does not need to know what parts are generated for the product, how the parts corresponding to each product are different from each other, how they are built, and how they constitute the product.
Object Construction
In some cases, an object has some important properties and cannot be used as a complete product until they have no proper values. For example, an email contains the sender address, recipient address, subject, content, and appendix. However, this email cannot be sent before the minimum recipient address is assigned a value.
In some cases, some properties of an object must be assigned values in a certain order to make sense. Before a property is assigned a value, another property cannot be assigned a value. These situations make the construction of nature involve complex business logic. At this time, this object is equivalent to a product to be built, and these properties are equivalent to the parts of the product, the process of building the product is the process of building parts. Due to the complex process of building parts, the construction process of these parts is often "Externalized" to another object called builder, the builder object returned to the client is a product object where all parts have been built.
The construction model creates all the parts one by one using a director object and a specific builder object to create a complete product object. The builder mode hides the structure of the product and the construction process of the parts of the product from the client, and separates the responsibility for directing the construction process from the responsibility of the specific parts of the builder, achieve responsibility division and encapsulation.
Construction mode structure
In this schematic system, the final product has only two parts, namely, Part1 and Part2. There are two corresponding construction methods: buildpart1 () and buildpart2 (). At the same time, we can see that this mode involves four roles:
Abstract builder role:An abstract interface is provided to standardize the construction of each component of the product object. Generally, this interface is independent from the business logic of the application. The concretebuilder role is used to directly create a product object. The specific builder class must implement the 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 is consistent with the number of construction methods. In other words, how many parts are there is a corresponding construction method.
Specific builder role:Classes that are closely related to applications are used to create product instances under application calls. The tasks to be completed by this role include: 1. Implement the interface declared by the abstract Builder, and provide step-by-step operations for creating product instances. 2. Provide product instances after the construction is completed.
Ctor role:The class that assumes this role calls the specific builder role to create a product object. It should be pointed out that the director role does not have specific knowledge of the product class, and the specific knowledge of the product class is actually the specific builder role.
Product role:Products are complex objects during construction. Generally, a system has more than one product class, and these product classes do not necessarily have a common interface, but they can be completely unrelated.
The Director role is a role that deals with clients. The Director divides the client product creation request into the construction request for each part, and then delegates the request to the specific builder role. The specific builder role is used for specific construction, but is not known to the client.
Generally, each product class has a specific builder class. These products should have the same number of parts, and each part has a corresponding construction method in all builder roles.
Source code
Product
Package COM. bankht. builder;/*** @ Author: -AK47 * @ Creation Time: 10:08:32 ** @ Class description: */public class product {/*** defines some product operations */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
Package COM. bankht. builder;/*** @ Author: -AK47 * @ Creation Time: 10:09:13 ** @ Class description: abstract builder class builder */public interface builder {public void buildpart1 (); Public void buildpart2 (); Public Product retrieveresult ();}
Concretebuilder
Package COM. bankht. builder;/*** @ Author: -AK47 * @ Creation Time: 10:09:33 ** @ Class description: specific builder class concretebuilder */public class concretebuilder implements builder {private product Product = new product ();/*** product part construction method 1 */@ overridepublic void buildpart1 () {// build the first part product of the product. setpart1 ("No.: 9527");}/*** product part construction method 2 */@ overridepublic void buildpart2 () {// build the product's second part product. setpart2 ("Name: XXX");}/*** product return Method */@ overridepublic product retrieveresult () {return product ;}}
Director class ctor
Package COM. bankht. builder;/*** @ Author: -AK47 * @ Creation Time: 10:12:10 ** @ Class description: director class director */public class director {/*** holds the builder object currently needed */private Builder;/*** constructor, input builder object ** @ Param builder * builder object */public director (Builder) {This. builder = builder;}/*** product construction method, which calls each part Construction Method */Public void construct () {builder. buildpart1 (); builder. buildpart2 ();}}
Client
Package COM. bankht. builder;/*** @ Author: -AK47 * @ Creation Time: 10:12:29 ** @ Class description: client class client */public class client {public static void main (string [] ARGs) {Builder = new concretebuilder (); Director dire= new director (builder); Director. construct (); product Product = builder. retrieveresult (); system. out. println (product. getpart1 (); system. out. println (product. getpart2 ());}}Sequence Chart
The client is responsible for creating directors and specific builder objects. Then, the client handed over the specific builder object to the Director. The director operated on the specific builder and started to create the product. After the product is completed, the builder returns the product to the client.
The task of creating a specific builder object is handed over to the client rather than the Director object, in order to change the coupling between the Director object and the specific builder object to dynamic, this allows the Director object to manipulate any of several specific builder objects.
Use Cases
Suppose there is an e-Magazine system that regularly sends e-magazines to users' email mailboxes. You can subscribe to an electronic magazine through the web page or through the web page. When the customer starts to subscribe, the system sends an email to send a greeting. When the customer ends the subscription, the system sends an email to send a greeting. In this example, the system is responsible for sending "welcome" and "farewell" emails.
In this example, the product category is the "welcome" and "farewell" emails sent to a customer, as shown in.
Although each product class in this example has a common interface, this is only unique in this example and does not represent the characteristics of the construction mode. The build mode can be applied to product classes with completely different interfaces. In most cases, I don't know what the final product is. Therefore, in the standard construction mode, it is generally not necessary to define abstract interfaces for the product, because the final products are very different, defining public interfaces for these products is almost meaningless.
This is the class diagram of the system.
This system includes clients, directors, abstract builders, welcomebuilder and goodbyebuilder, and products (welcomemessage and goodbyemessage.
Source code
Abstract class automessage source code. The send () operation is just schematic and does not provide any email sending code.
Package COM. bankht. builder. mail; import Java. util. date;/*** @ Author: -AK47 * @ Creation Time: 02:31:38, December 25, ** @ Class description: abstract class automessage source code. The send () operation is only schematic, no email sending code is provided. */Public abstract class automessage {// recipient address private string to; // sender address private string from; // Title private string subject; // content private string body; // sending 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 ("Sending 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 type: welcomemessage
Package COM. bankht. builder. mail;/*** @ Author: -AK47 * @ Creation Time: 02:32:16, December 25, ** @ Class description: specific product class welcomemessage */public class welcomemessage extends automessage {/*** No parameter constructor */Public welcomemessage () {system. out. println ("Send Welcome Message ");}}
Goodbyemessage
Package COM. bankht. builder. mail;/*** @ Author: -AK47 * @ Creation Time: 02:32:45, December 25, ** @ Class description: specific product class goodbyemessage */public class goodbyemessage extends automessage {/*** No parameter constructor */Public goodbyemessage () {system. out. println ("Send farewell message ");}}
Abstract builder class
Package COM. bankht. builder. mail; import Java. util. date;/*** @ Author: -AK47 * @ Creation Time: 02:33:07, December 25, ** @ Class description: Abstract builder class */public abstract class builder {protected automessage MSG; // Title part construction method public abstract void buildsubject (); // content part construction method public abstract void buildbody (); // public void buildto (string to) {MSG. setto (to);} // sender part construction method public void buildfrom (string from) {MSG. setfrom (from);} // creation method of the sending time part public void buildsenddate () {MSG. setsenddate (new date ();}/*** after the email product is complete, use this method to send an email. This method is equivalent to the product return Method */Public void sendmessage () {MSG. send ();}}
Specific builder welcomebuilder
Package COM. bankht. builder. mail;/*** @ Author: -AK47 * @ Creation Time: 02:33:36, December 25, ** @ Class description: specific builder welcomebuilder */public class welcomebuilder extends builder {public welcomebuilder () {MSG = new welcomemessage () ;}@ overridepublic void buildbody () {// todo auto-generated method stubmsg. setbody ("Welcome content") ;}@ overridepublic void buildsubject () {// todo auto-generated method stubmsg. setsubject ("Welcome title ");}}
Specific builder goodbyebuilder
Package COM. bankht. builder. mail;/*** @ Author: -AK47 * @ Creation Time: 02:34:15, December 25, ** @ Class description: specific builder goodbyebuilder */public class goodbyebuilder extends builder {public goodbyebuilder () {MSG = new goodbyemessage () ;}@ overridepublic void buildbody () {// todo auto-generated method stubmsg. setbody ("Farewell content") ;}@ overridepublic void buildsubject () {// todo auto-generated method stubmsg. setsubject ("Farewell title ");}}
Director, this class provides a construct () method that calls the builder's construction method, including buildto (), buildfrom (), buildsubject (), buildbody (), buildsenddate (), and so on, part of the creation of product objects, both automessage objects.
Package COM. bankht. builder. mail;/*** @ Author: -AK47 * @ Creation Time: 02:34:52 ** @ Class description: ctor dire, this class provides a construct () method, this method calls the builder's construction method, * including buildto (), buildfrom (), buildsubject (), buildbody (), buildsenddate (), and so on, and * creates product objects in some parts, automessage object. */Public class director {Builder;/*** constructors with parameters */public director (Builder) {This. builder = builder;}/*** product construction method, which calls 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
Package COM. bankht. builder. mail;/*** @ Author: -AK47 * @ Creation Time: 02:35:36, December 25, ** @ Class description: client client */public class client {public static void main (string [] ARGs) {Builder = new welcomebuilder (); Director ctor = new director (builder); Director. construct ("toAddress@126.com", "fromAddress@126.com ");}}
Run:
Send welcome message recipient address: toAddress@126.com sender address: fromAddress@126.com title: Welcome title content: Welcome content sent date: Mon Jun 25 14:47:37 CST 2012
If the code in client. Java is
Changed:
Builder builder = new GoodbyeBuilder();
The running result is changed:
Send farewell message recipient address: toAddress@126.com sender address: fromAddress@126.com title: farewell title content: Farewell content send Date: Mon Jun 25 14:49:29 CST 2012
The construction model is divided into two important parts:
1. One part is the builder interface, which defines how to build each part, that is, how to implement each part function, and how to assemble these parts into the product;
2. The other part is director, which knows how to combine to build a product. That is to say, Director is responsible for the overall build algorithm and is generally executed in steps.
Regardless of the change,The construction model has two parts: Component Construction and product assembly, and integral building algorithm.. It is very important to understand this, because in the construction model, we emphasize the fixed overall construction algorithm, while flexibly expanding and switching the specific structure of components and product assembly methods.
To put it bluntly, the focus of the construction model is to separate the Construction Algorithm and specific construction implementation, so that the construction algorithm can be reused. The specific construction implementation can be easily expanded and switched, so that different product objects can be flexibly combined.
Building complex objects using the build Mode
Considering such a practical application, we need to create an insurance contract object. Many attribute values have constraints, and the created objects must meet these constraints. For example, an insurance contract can be signed with an individual or a company, but an insurance contract cannot be signed with an individual or company at the same time. There are many such constraints in this object. Using the construction mode to construct complex objects usually simplifies the construction mode. because the goal is clear, it is to create a complex object, therefore, proper simplification will make the program more concise. It is roughly simplified as follows:
● Because an object is created in builder mode, there is no need to define another builder interface and a specific builder class is provided directly.
● There may be many different options and steps for creating a complex object. simply remove the "director" and combine the director's functions with the client functions. That is to say, the client is equivalent to the Director, who guides the builder class to build complex objects.
Insurance Contract
Package COM. bankht. builder. contract;/*** @ Author: -AK47 * @ Creation Time: 02:55:52, December 25, ** @ Class description: insurance Contract type * // **** insurance contract object */@ suppresswarnings ("UNUSED") public class insurancecontract {// Insurance Contract No. Private string contractid; /*** name of the insured, the same insurance contract, either signed with the personnel or with the company, * That Is: the "insured" and "Insurance Company" attributes cannot have the value */private string personname at the same time; // the name of the insurance company private string companyName; // The effective date of the Insurance Service. Private long begindate; // the expiration date of the Insurance Service., Will definitely be greater than the effective date of the insurance start private long enddate; // other data private string otherdata; // private constructor 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;}/*** insurance contract operations */Public void someoperation () {Boolean Si Gnperson = (personname! = NULL & personname. Trim (). Length ()> 0); Boolean signcompany = (companyName! = NULL & companyName. trim (). length ()> 0); system. out. println ("the currently operating insurance contract number is [" + this. contractid + "]"); If (signperson) {system. out. println ("the insured person is an individual, personal name:" + this. personname);} If (signcompany) {system. out. println ("Insurance Company, company name:" + this. companyName) ;}} public static class concretebuilder {private string contractid; private string personname; private string companyName; private long begindate; private Lo Ng enddate; private string otherdata;/*** constructor, required parameter ** @ Param contractid * insurance contract number * @ Param begindate * Effective date of the insurance contract * @ Param enddate * Expiration date of the insurance contract */Public concretebuilder (string contractid, long begindate, long enddate) {This. contractid = contractid; this. begindate = begindate; this. enddate = enddate;} // name of the insured person public concretebuilder setpersonname (string personname) {This. personname = personname; Return this;} // name of the insured company public concretebuilder setcompanyname (string companyName) {This. companyName = companyName; return this;} // other data public concretebuilder setotherdata (string otherdata) {This. otherdata = otherdata; return this;}/*** construct the real object and return ** @ return the constructed insurance contract object */Public insurancecontract build () {If (contractid = NULL | contractid. trim (). length () = 0) {Throw new illegalargumentexception (" Contract No. cannot be blank ");} 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 individuals and companies ");} if (signperson = false & signcompany = false) {Throw new illegalargumentexception ("an insurance contract cannot be signed");} If (begindate <= 0) {Throw new illegalargumentexception ("an insurance contract must have a date starting to take effect");} If (enddate <= 0) {Throw new illegalargumentexception ("an insurance contract must have an expiration date");} If (enddate <begindate) {Throw new illegalargumentexception ("the expiration date of an insurance contract must be later than the effective date");} return New insurancecontract (this );}}}
Client type
Package COM. bankht. builder. contract;/*** @ Author: -AK47 * @ Creation Time: 02:56:56, December 25, ** @ Class description: client class */public class client {public static void main (string [] ARGs) {// create the builder object insurancecontract. concretebuilder builder = new insurancecontract. concretebuilder ("9527", 123l, 456l); // set the required data, and then build the insurance contract object insurancecontract contract = builder. setpersonname ("-AK47 "). setotherdata ("test "). build (); // insurancecontract contract = builder. setcompanyname ("Digital China "). setotherdata ("test "). build (); // The contract method for operating the insurance contract object. someoperation ();}}
Run:
The number of the insurance contract currently in operation is [9527]. The insured person is an individual. His/Her name is: special soldier-AK47.
If you change client. Java:
Insurancecontract contract = builder. setcompanyname ("Digital China"). setotherdata ("test"). Build ();
The running result is:
The currently operating Insurance Contract No. [9527] is the insurance company. Company Name: Digital China
In this example, the specific 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, it directly uses new to build product objects. In addition, this builder is used to create the constructed object, and you do not need to create a separate class.
When to use the build Mode
1. The product objects to be generated have a complex internal structure. Each internal component can be an object or an integral part of an object (that is, a product object.
2. The attributes of the product objects to be generated are mutually dependent. The construction mode can enforce a step-by-step construction process. Therefore, if one attribute of a product object must be assigned a value after another attribute, using the construction mode is a good design concept.
3. Some other objects in the system will be used during object creation. These objects are not easy to obtain during product object creation.