Builder mode: Builder (converted from aliang. Net)

Source: Internet
Author: User
Builder Mode

The builder model can separate the internal appearance of a product from the product generation process, so that a building process can generate product objects with different internal appearances.

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 of the object is equivalent to the parts of the product, the process of building the product is the process of combining Parts. Due to the complex process of assembling parts, the combination process of these parts is often "Externalized" into an object called builder, the builder returned the product object to the client after all parts have been built.

Naming considerations

The reason why "Builder" is used instead of "Builder" is that "Builder" is more appropriate to "CREATE" or "generate" because it is used to produce products with parts.

Ii. Builder mode structure:


Builder role: provides an abstract interface to regulate the construction of each component of a 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 method required by the specific builder class to implement this interface: one is the construction method, and the other is the result return method.

Specific builder role: the role is for the ApplicationProgramClosely related classes, which create product instances under application calls. The main tasks completed by this role include:

Implements the interfaces provided by the builder role and completes the process of creating product instances step by step.
After the construction process is complete, provide the product instance.
Ctor role: the class that acts as the role calls a specific builder role to create a product object. The director does not have the specific knowledge of the product class. What really possesses the specific knowledge of the product class is the specific builder object.

Product role: a product is a complex object during construction.

The mentor role is a role that deals with clients. The Director role divides the client product creation request into the construction request for each part, and then delegates these requests to the specific builder role. The specific builder role is used for specific construction, but is not known to the client.

3. program example:

This program demonstrates the builder Mode Step by step to complete the complex component product process. You can control the generation process and generate different objects.

 // Builder pattern -- Structural example  Using System; Using System. collections; // "Director"  Class Director { // Methods    Public   Void Construct (Builder) {builder. buildparta (); builder. buildpartb ();}} // "Builder"  Abstract   Class Builder { // Methods    Abstract   Public   Void Buildparta (); Abstract   Public   Void Buildpartb (); Abstract   Public Product getresult ();} // "Concretebuilder1"  Class Concretebuilder1: builder { // Fields   Private Product product; // Methods    Override   Public   Void Buildparta () {Product = New Product (); product. Add ( "Parta" );} Override   Public   Void Buildpartb () {product. Add ( "Partb" );} Override   Public Product getresult (){ Return Product ;}} // "Concretebuilder2"  Class Concretebuilder2: builder { // Fields   Private Product product; // Methods    Override   Public   Void Buildparta () {Product = New Product (); product. Add ( "Partx" );} Override   Public   Void Buildpartb () {product. Add ( "Party" );} Override   Public Product getresult (){ Return Product ;}} // "Product"  Class Product { // Fields Arraylist parts =New Arraylist (); // Methods    Public   Void Add ( String Part) {parts. Add (part );} Public   Void Show () {console. writeline ( "Product parts -------" ); Foreach ( String Part In Parts) console. writeline (Part );}} /**/ /// <Summary> /// Client Test  /// </Summary>  Public   Class Client { Public  Static   Void Main ( String [] ARGs ){ // Create director and builders Director dire= New Director (); builder b1 = New Concretebuilder1 (); builder b2 = New Concretebuilder2 (); // Construct two products Director. Construct (B1); product p1 = b1.getresult (); p1.show (); Director. Construct (B2); product P2 = b2.getresult (); p2.show ();}}

4. Activity sequence of builder mode:


The client is responsible for creating the mentor and specific builder objects. Then, the customer handed over the specific builder object to the mentor. The customer ordered the mentor to manipulate the builder to start creating the product. After the product is created, the builder returns the product to the client.

V. Implementation of the builder mode:

The following programCodeDemonstrate how the shop object uses vehiclebuilders to build different transportation tools. This example uses the builder mode to sequentially construct different parts of a vehicle.

 // Builder pattern -- real world example  Using System; Using System. collections; // "Director"  Class Shop { // Methods    Public   Void Construct (vehiclebuilder) {vehiclebuilder. buildframe (); vehiclebuilder. buildengine (); vehiclebuilder. buildwheels (); vehiclebuilder. builddoors ();}} // "Builder" Abstract   Class Vehiclebuilder { // Fields    Protected Vehicle vehicle; // Properties    Public Vehicle vehicle { Get { Return Vehicle ;}} // Methods    Abstract   Public   Void Buildframe (); Abstract   Public   Void Buildengine (); Abstract   Public   Void Buildwheels (); Abstract  Public   Void Builddoors ();} // "Concretebuilder1"  Class Motorcyclebuilder: vehiclebuilder { // Methods    Override   Public   Void Buildframe () {vehicle = New Vehicle ( "Motorcycle" ); Vehicle [ "Frame" ] = "Motorcycle Frame" ;} Override   Public   Void Buildengine () {vehicle [ "Engine" ] = "500 cc" ;}Override   Public   Void Buildwheels () {vehicle [ "Wheels" ] = "2" ;} Override   Public   Void Builddoors () {vehicle [ "Doors" ] = "0" ;}} // "Concretebuilder2"  Class Carbuilder: vehiclebuilder { // Methods    Override   Public   Void Buildframe () {vehicle = New Vehicle ( "Car" ); Vehicle ["Frame" ] = "Car Frame" ;} Override   Public   Void Buildengine () {vehicle [ "Engine" ] = "2500 cc" ;} Override   Public   Void Buildwheels () {vehicle [ "Wheels" ] = "4" ;} Override   Public   Void Builddoors () {vehicle [ "Doors" ] = "4" ;}} // "Concretebuilder3" Class Scooterbuilder: vehiclebuilder { // Methods    Override   Public   Void Buildframe () {vehicle = New Vehicle ( "Scooter" ); Vehicle [ "Frame" ] = "Scooter frame" ;} Override   Public   Void Buildengine () {vehicle [ "Engine" ] = "None" ;} Override   Public   Void Buildwheels () {vehicle ["Wheels" ] = "2" ;} Override   Public   Void Builddoors () {vehicle [ "Doors" ] = "0" ;}} // "Product"  Class Vehicle { // Fields    Private   String Type; Private Hashtable parts = New Hashtable (); // Constructors    Public Vehicle ( String Type ){ This . Type = type ;} // Indexers    Public   Object   This [ String Key] { Get { Return Parts [Key];} Set {Parts [Key] = value ;}} // Methods    Public   Void Show () {console. writeline ( "---------------------------" ); Console. writeline ( "Vehicle type :" + Type); console. writeline ( "Frame :" + Parts [ "Frame" ]); Console. writeline ("Engine :" + Parts [ "Engine" ]); Console. writeline ( "# Wheels :" + Parts [ "Wheels" ]); Console. writeline ( "# Doors :" + Parts [ "Doors" ]) ;}} /**/ /// <Summary> /// Builderapp Test  /// </Summary>  Public   Class Builderapp { Public   Static   Void Main ( String [] ARGs ){ // Create shop and vehicle builders Shop shop =New Shop (); vehiclebuilder b1 = New Scooterbuilder (); vehiclebuilder b2 = New Carbuilder (); vehiclebuilder B3 = New Motorcyclebuilder (); // Construct and display vehicles Shop. construct (B1); b1.vehicle. show (); shop. construct (B2); b2.vehicle. show (); shop. construct (B3); b3.vehicle. show ();}}

6. Evolution of builder Models

The builder mode can evolve into multiple forms during use.

Omitting the abstract builder role

If you only need a specific builder in the system, you can omit the abstract builder. The code may be as follows:

// "Director"ClassDirector {PrivateConcretebuilder;// MethodsPublic VoidConstruct () {builder. buildparta (); builder. buildpartb ();}

The instructor role is omitted.

If there is only one specific builder, if the abstract builder role has been omitted, you can also omit the instructor role. Let the builder role assume the dual role of mentor and builder. The code may be as follows:

Public ClassBuilder {PrivateProduct =NewProduct ();Public VoidBuildparta (){// Some code here}Public VoidBuildpartb (){// Some code here}PublicProduct getresult (){ReturnProduct ;}Public VoidConstruct () {buildparta (); buildpartb ();}}

At the same time, the client also needs to make corresponding adjustments, as shown below:

 
Public ClassClient {Private StaticBuilder;Public Static VoidMain () {builder =NewBuilder (); builder. Construct (); product Product = builder. getresult ();}}

Stringbuilder in C # is an example.

7. Under what circumstances should the builder mode be used?

The builder mode should be used in the following situations:

1. The product objects to be generated have a complex internal structure.
2. The properties of the product objects to be generated are mutually dependent. The Builder mode can force the generation order.
3. Some other objects in the system will be used during object creation. These objects are not easy to obtain during product object creation.

The builder mode has the following effects:

1. The use of the construction model allows the internal appearance of the product to change independently. By using the builder mode, the client does not have to know the details of the product composition.
2. Each builder is relatively independent of other builders.
3. The final product built by the model is easier to control.

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.