Design Pattern 09-builder pattern of design pattern (builder pattern) is also called builder pattern (creation pattern)

Source: Internet
Author: User
1. Scenario Mode

When discussing the factory method mode, I mentioned an application framework for exporting data, but I didn't discuss how to implement each method for exporting text. Now let's solve this problem.
Assume that the exported file is divided into three parts, the file header, the end of the file, and the file body, regardless of the format.
Document Header: Number of the branch or outlet, date of data export
End of file: output
File body: Table Name
Export data to text files and XML files
2. Simulate header file content in code 2.1

Package demo07.builder. example1;/*** the object that describes the content output to the file header */public class exportheadermodel {/*** branch or outlet Number */private string depid; /*** Date of data export */private string exportdate; Public String getdepid () {return depid;} public void setdepid (string depid) {This. depid = depid;} Public String getexportdate () {return exportdate;} public void setexportdate (string exportdate) {This. exportdate = exportdate ;}}
2.2 Output Data Objects
Package demo07.builder. example1;/*** the object describing the output data */public class exportdatamodel {/*** product no. */private string productid; /***** sales price */private double price;/***** sales quantity */private double amount; Public String getproductid () {return productid ;} public void setproductid (string productid) {This. productid = productid;} public double getprice () {return price;} public void setprice (double price) {This. price = price;} public double getamount () {return amount;} public void setamount (double amount) {This. amount = amount ;}}
2.3 objects at the end of the file
Package demo07.builder. example1;/*** specifies the object that is output to the end of the file */public class exportfootermodel {/*** /*/private string exportuser; Public String getexportuser () {return exportuser;} public void setexportuser (string exportuser) {This. exportuser = exportuser ;}}
2.4 export data to an object in a text file
Package demo07.builder. example1; import Java. util. collection; import Java. util. map; /*** object for exporting data to a text file */public class exporttotxt {/*** export data to a text file ** @ Param ehm * file header content * @ Param mapdata * data content * @ Param EFM * content at the end of the file */Public void Export (exportheadermodel ehm, map <string, collection <exportdatamodel> mapdata, exportfootermodel EFM) {// used to record the final output file content stringbuffer buffer = new stringbuffer (); // 1: first, splice the buffer of the file header. append (Ehm. getdepid () + "," + Ehm. getexportdate () + "\ n"); // 2: splice the object content for (string tblname: mapdata. keyset () {// concatenate the table name buffer first. append (tblname + "\ n"); // then concatenate the specific data cyclically for (exportdatamodel EDM: mapdata. get (tblname) {buffer. append (EDM. getproductid () + "," + EDM. getprice () + "," + EDM. getamount () + "\ n") ;}// 3: splice the content buffer at the end of the file. append (EFM. getexportuser (); // In order to demonstrate simplicity, the code of the output file is not written here. // output the output content to the console to see the system. out. println ("content output to a text file: \ n" + buffer );}}
2.5 export data to an XML Object
Package demo07.builder. example1; import Java. util. collection; import Java. util. map; /*** export data to the XML file object */public class exporttoxml {/*** export data to the XML file ** @ Param ehm * file header content * @ Param mapdata * data content * @ Param EFM * content at the end of the file */Public void Export (exportheadermodel ehm, map <string, collection <exportdatamodel> mapdata, exportfootermodel EFM) {// used to record the final output file content stringbuffer buffer = new stringbuffer (); // 1: splice first Buffer. append ("<? XML version = '1. 0' encoding = 'gb2312 '?> \ N "); buffer. append ("<Report> \ n"); buffer. append ("2.6 client Test
Package demo07.builder. example1; import Java. util. arraylist; import Java. util. collection; import Java. util. hashmap; import Java. util. map; public class client {public static void main (string [] ARGs) {// prepare test data exportheadermodel ehm = new exportheadermodel (); Ehm. setdepid ("one branch"); Ehm. setexportdate ("2010-05-18"); Map <string, collection <exportdatamodel> mapdata = new hashmap <string, collection <exportdatamodel> (); collection <exportdatamodel> Col = new arraylist <exportdatamodel> (); exportdatamodel edm1 = new exportdatamodel (); edm1.setproductid ("Product 001"); edm1.setprice (100 ); edm1.setamount (80); exportdatamodel edm2 = new exportdatamodel (); edm2.setproductid ("Product 002"); edm2.setprice (99); edm2.setamount (55); // assemble data into Col. add (edm1); Col. add (edm2); mapdata. put ("sales record table", col); exportfootermodel EFM = new exportfootermodel (); EFM. setexportuser ("Zhang San"); // test the output to the text file exporttotxt totxt = new exporttotxt (); totxt. export (ehm, mapdata, EFM); // test the output to the XML file exporttoxml toxml = new exporttoxml (); toxml. export (ehm, mapdata, EFM );}}
3. Problem

After carefully observing the above implementation, we will find that the steps are basically the same in both the output text file and the XML file, which are roughly divided into four steps:
1. splice the content of the header file
2. splice the object content
3. contents at the end of the spliced File
4. output the spliced content to the file.
What does this mean? The processing steps are basically the same for different output formats. However, the specific implementation of each step is different.
Therefore, we should extract public processing processes and quickly switch between different output formats.
4. Solution 4.1 generator mode definition: (also called builder Mode)

Separates the construction of a complex object from its representation so that different representations can be created during the same construction process.
4.2 structure of the generator Mode

 
5. Sample Code 5.1 In GENERATOR mode interface of the product object constructed

Package demo07.builder. example2;/*** interface of the constructed product object */public interface product {// define product operations}
5.2 builder interface, which defines the operations for each part required to create a product object
Package demo07.builder. example2;/*** builder interface, which defines the operation of each part required for creating a product object */public interface builder, build Part 1 */Public void buildpart1 ();/*** schematic method, build part 2 */Public void buildpart2 ();/*** schematic method, build Part 3 */Public void buildpart3 ();}
5.3 Specific builder implementation objects
Package demo07.builder. example2;/*** specific builder implementation object */public class concretebuilder implements builder {/*** final builder build product object */private product resultproduct; /*** get the final product object built by the builder ** @ return the final product object built by the builder */Public Product getresult () {return resultproduct ;} @ overridepublic void buildpart1 () {// This. operations for adding a component in resultproduct} @ overridepublic void buildpart2 () {// related to this. operations for adding a component in resultproduct} @ overridepublic void buildpart3 () {// related to this. operations on adding components to resultproduct }}
5.4 mentor
Package demo07.builder. example2;/*** instructor, guides you to use the builder interface to build the product object */public class ctor {/*** holding the builder object currently needed */private Builder; /*** constructor method to pass in the builder object ** @ Param builder * builder object */public director (Builder) {This. builder = builder;}/*** method to instruct the builder to build the final product object */Public void construct () {// use the builder interface to build the final product object builder. buildpart1 (); builder. buildpart2 (); builder. buildpart3 ();}}
5.5 client code
Package demo07.builder. example2; public class client {public static void main (string [] ARGs) {// The Builder for implementation (this is the changed part) concretebuilder = new concretebuilder (); // ctor diredire= new director (concretebuilder); // execution method director. construct (); // output the product result system. out. println (concretebuilder. getresult ());}}
6 Generator mode thinking 6.1 my own thinking

If you observe it carefully, you will find a problem. Why do you have to be a mentor? Is it okay to build a component merging method directly in builder? At the beginning, I thought this would work,In fact, this is also feasible.. However, if there are multiple builders, the methods of each builder may not be the same. Do you need to know the detailed functions of each builder? So if there is a guide to "Guide", when you need to expand the function, you just need to add a method in the mentor, this demonstrates the minimum knowledge principle. For example, if I want to build part 1 and part 2, I can build a method in the mentor as follows, therefore, there is no need to know the specific functions of the builder for client calls, and the most appropriate building sequence. This is not beautiful. To put it bluntlyBuilder is used to design detailed components, and the mentor is used to guide assembly of components. For fixed interface builder with detailed methods, do not add or delete methods for its specific implementation classes,All changes are placed in the ctor section. However, for different builders, I only need to rewrite the methods in the builder without changing the Director section. This has great advantages, reducing coupling and increasing cohesion. Layered thinking is obvious.

/*** Probe method to guide the builder to build the final product object */Public void constructother () {// build the final product object Builder by using the builder interface. buildpart1 (); builder. buildpart2 ();}

6.2 Call Sequence diagram of generator Mode

 
6.3 Example of rewrite scenario mode in generator Mode

Because the generator mode is relatively simple, and the scenario mode code is complicated, I will not post this code. You can compare the sample code in the generator mode to rewrite the scenario mode, which is very simple, I believe everything I think is simple.
6.4 center of gravity of the generator Mode

Focus:
1. Separate construction algorithms and specific construction implementation
2. constructor algorithms can be reused to facilitate expansion and switching
3. the layered thinking is obvious, separating general and specific implementations.
4. The Builder interface is responsible for constructing and assembling components in detail.
5. The director interface is responsible for guiding product assembly.
6.5 nature of the generator model

Essentially: separating the overall construction algorithm and Component Construction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.