Builder mode for creating design patterns

Source: Internet
Author: User
Tags constructor static class
1 Builder Mode Concepts 1.1 Introduction

The builder mode is a step-by-step creation of a complex object that allows the user to control the object's construction process more finely without knowing the internal build details. This pattern is designed to decouple the process of building complex objects from its components, separating the representation of the build process from the part.
The builder model consists of a clear division of labor, an abstract builder, a concrete builder, a conductor, and, of course, a specific product. So we take a software PRODUCT as an example: a technical director is an abstract builder, he communicates with the product manager, knows what kind of product to make, and the programmer is the concrete laborer, the technical director says what you do, and the conductor is the company's product manager, who is responsible for communicating with the user and understanding the customer's needs. 1.2 Definitions

Separating the construction of a complex object from its representation allows the same build process to create different representations. 1.3 Use the same method of the scene, different execution order, produce different event results, multiple parts or parts can be assembled into an object, but the result is different, the product class is very complex, or the order of call in the product class produces different performance, This is a good time to use builder mode, when initializing an object is particularly complex, such as many parameters, and many parameters have default values. 2 Builder Mode UML class diagram General

Role Description: product--Product class: abstract class of product. builder--abstract class, standardize the building of products, is generally the implementation of the specific components of the child class process. concretebuilder--Concrete Builders. director--conductor, unified assembly process (can be omitted).

3 common mode code

(1) Product category

/**
 * Product class
 *
/public class product {public
    void dosomething () {
        //standalone Business processing
    }
}

(2) Abstract builders ' class

/**
 * Abstract Builder
 * If there are multiple product classes there are several concrete builders, and the multiple product classes have the same interface or abstract class *
/Public abstract class Builder { 
    // The Setpart method is the configuration of the parts, setting up different parts of the product, or different assembly order, to produce different product public
    abstract void Setpart (); 

    Build product public
    abstract product buildproduct ();
}

(3) Concrete Builders ' class

/**
 * Concrete Builder *
/public class Concreteproduct extends Builder {
    private Product Product = new Product () ; 

    Set product part public
    void Setpart () {
        //logical processing within a product class    
    }

    //Build a product public products
    Buildproduct () {
        return product;
    }
}

(4) conductor (director) class

/**
 * Conductor Class
 * The conductor class plays a role in encapsulation, avoiding the high-level module reaching into the builder's internal implementation class */public
class Director {
    //building a different product
    private Builder builder = new Concreteproduct (); 

    Public Product getaproduct () {
        builder.setpart ();

        Set different parts to produce different products
        return builder.buildproduct ();}

}
4 Builder Mode variants (common) 4.1 General
public class Person {private String name;
    private int age;
    private double height;

    private double weight;
    Public person (String name) {this.name = name;
        The public person (String name, int age) {this.name = name;
    This.age = age;
        The public person (String name, int age, double height) {this.name = name;
        This.age = age;
    This.height = height;
        The public person (String name, int age, double height, double weight) {this.name = name;
        This.age = age;
        This.height = height;
    This.weight = weight;
    } public String GetName () {return name;
    } public void SetName (String name) {this.name = name;
    } public int Getage () {return age;
    public void Setage (int.) {this.age = age;
    } public double GetHeight () {return height;
    public void SetHeight (double height) {this.height = height;} public double Getweight () {return weight;
    } public void Setweight (double weight) {this.weight = weight; }
}

Create the individual objects you want:

Person P1=new person ();
Person P2=new person ("Zhang San");
Person P3=new person ("John Doe",);
Person P4=new person ("Harry", 21,180);
Person P5=new person ("Zhao Liu", 17,170,65.4);

Can imagine the disadvantage of such a creation, the most intuitive is the four parameters of the constructor of the last side of the two parameters exactly what meaning, not good readability, if you do not click to see the source, do not know which is weight which is the height. Another problem is that when there are a lot of parameters, writing this constructor will be very troublesome, at this point, if you change the angle, try the builder mode, you will find that the readability of the code went up suddenly. 4.2 Using the builder mode

public class Person {private String name;
    private int age;
    private double height;

    private double weight;
        private person (builder builder) {this.name=builder.name;
        This.age=builder.age;
        This.height=builder.height;
    This.weight=builder.weight;
    } public String GetName () {return name;
    } public void SetName (String name) {this.name = name;
    } public int Getage () {return age;
    public void Setage (int.) {this.age = age;
    } public double GetHeight () {return height;
    public void SetHeight (double height) {this.height = height;
    } public double Getweight () {return weight;
    } public void Setweight (double weight) {this.weight = weight;
        } Static class builder{private String name;
        private int age;
        private double height;

        private double weight; Public Builder SetName (String name) {this.name=name;
        return this;
            Public Builder setage (int age) {this.age=age;
        return this;
            Public Builder setheight (double height) {this.height=height;
        return this;
            Public Builder setweight (double weight) {this.weight=weight;
        return this; Public person Build () {return new person (this);//build () Return person object}}}

In the builder class, you define a variable that is identical to the person class, set the property value by a series of member functions, but the return value is this, which is the builder object, and finally provides a build function to create the person object. The person object is returned, and the corresponding constructor is defined in the person class, that is, the constructor's argument is the Builder object, then assigns its own member variable in turn, and the corresponding value is the value in the Builder object. In addition, the function of member functions in the Builder class to return the builder object itself is to allow it to support chained calls, which greatly enhances the readability of the code. You can then create a person class like this.

person person = new person (). Builder ().
      setName ("Zhang San")
      . Setage (. SetHeight (178.5).
      setweight (67.4)
      . Build ();
4.3 summary

(1) Define a static internal class builder, with the same internal member variables as the outer class
The builder class is used by a series of methods to assign values to member variables and to return the current object itself (this).
(2) The Builder class provides a build method or create method for creating the corresponding outer class, which internally invokes a private constructor of the outer class, which is the internal class builder.
(3) The outer class provides a private constructor that is called by the inner class to complete the assignment of the member variable in the constructor, taking the value as the corresponding value in the Builder object. 5 Builder Mode Combat

(1) Product Category--Explore the app

/**
 * Product Class--Explore app */Public
class product {public
    static final String android = "Android";
    public static final String iOS = "ios";

    Private String appName;
    Private String appfuction;
    Private String Appsystem;

    Public String Getappname () {
        return appName;
    }

    public void Setappname (String appName) {
        this.appname = appName;
    }

    Public String getappfuction () {
        return appfuction;
    }

    public void Setappfuction (String appfuction) {
        this.appfuction = appfuction;
    }

    Public String Getappsystem () {
        return appsystem;
    }

    public void Setappsystem (String appsystem) {
        this.appsystem = Appsystem;
    }

    @Override public
    String toString () {
        return "Product [appname=" + AppName + ", appfuction=" + appfuction
                + ", appsystem=" + Appsystem + "]";
    }
}

(2) Abstract Builder class-technical supervisor (can be omitted)

/**
 * Abstract Builder Class-Technical director 
 * * Public
abstract class build {public abstract
    build Setappname (String appName); C4/>public abstract Build setappfuction (String appfuction);

    Public abstract Build Setappsystem (String appsystem);

    Public abstract Product Build ();
}

(3) Concrete builder class--Full stack programmer

/** * Concrete Builder class-Full stack programmer */public class Workbuilder extends Build {Private Product product;//product class private Innerpro Duct innerproduct = new innerproduct ();//Product buffer class @Override public Build setappname (String appName) {inner
        Product.setappname (AppName);
    return this;
        } @Override Public Build setappfuction (String appfuction) {innerproduct.setappfuction (appfuction);
    return this;
        } @Override Public Build setappsystem (String appsystem) {innerproduct.setappsystem (Appsystem);
    return this;
        @Override Public Product build () {Product = new product ();
        Product.setappname (Innerproduct.getappname ());
        Product.setappfuction (Innerproduct.getappfuction ());
        Product.setappsystem (Innerproduct.getappsystem ());
    return product;
        }/** * Product buffer class */Private class Innerproduct {private String appName;
        Private String appfuction;Private String Appsystem;
        Public String Getappname () {return appName;
        } public void Setappname (String appName) {this.appname = AppName;
        } public String Getappfuction () {return appfuction;
        } public void Setappfuction (String appfuction) {this.appfuction = appfuction;
        } public String Getappsystem () {return appsystem;
        } public void Setappsystem (String appsystem) {this.appsystem = Appsystem; }
    }
}

(4) Conductor Class-product manager (can be omitted)

/**
 * Conductor Class-Product Manager 
 *
/public class Director {public
    static product create (String system) {
        return new Workbuilder (). Setappsystem (System). Setappname ("probing"). Setappfuction ("Find a Sister"). Build ();}
}

(5) Client--Customer

/** * Client--Client */public class Client {public static void main (string[] args) {//client: I need a software that can shake and find her sister. Product Manager: Analysis to make a probe//technical supervisor: AppName: Probing, System: ios,android function: Shake a Shake find sister Product Android = Director.creat  
        E (product.android);  
        Product iOS = director.create (Product.ios);
        System.out.println (Android);

        System.out.println (iOS);  
        /** * Mutant Builders can only need concrete builders, abstract not, the conductor can also not * *//programmers feel too tired, pay less, do the most, finally decided to go alone.  
        Workbuilder Niubiprogremer = new Workbuilder (); Product androidbest = Niubiprogremer.setappname ("probing"). Setappsystem (product.android). Setappfuction ("Shake, Look for Sister").  
        Build ();
        Product iosbest = Niubiprogremer.setappname ("probing"). Setappsystem (Product.ios). Setappfuction ("Shake, Look for Sister"). Build ();
        System.out.println ("-------------------------------------------------------------------------------------");
        System.out.println (androidbest); System.out.println (IosbesT);   }  
}

(6) Results

Product [Appname=, appfuction=, appsystem=android]
product [appname= probe, appfuction= uniform search sister, Appsystem=ios ]
-------------------------------------------------------------------------------------
Product [ Appname=, appfuction= Shake, look for sister, Appsystem=android]
Product [appname= probe, appfuction= Shake, find sister, Appsystem=ios]
6 Builder mode in Android source code

In the Android source code, our most commonly used builder mode is Alertdialog.builder, which uses the builder to build complex Alertdialog objects. 6.1 alertdialog sequence diagram Analysis


6.2 Alertdialog Source Analysis

In the Android source code, our most commonly used builder mode is Alertdialog.builder, which uses the builder to build complex Alertdialog objects. A simple example is as follows:

(1) showdialog--shows the basic Alertdialog

Show basic Alertdialog private void ShowDialog (context context) {Alertdialog.builder Builder = new alertdial og.  
        Builder (context);  
        Builder.seticon (R.drawable.icon);  
        Builder.settitle ("Title");  
        Builder.setmessage ("Message"); Builder.setpositivebutton ("Button1", new Dialoginterface.onclicklistener () {Publi  
                    c void OnClick (Dialoginterface dialog, int whichbutton) {settitle ("Clicked Button1 on Dialog box");  
        }  
                });  Builder.setneutralbutton ("Button2", new Dialoginterface.onclicklistener () {public  
                    void OnClick (dialoginterface dialog, int whichbutton) {settitle ("Clicked Button2 on Dialog box");  
        }  
                }); Builder.setnegativebutton ("Button3", new Dialoginterface.onclicklistener () {Publi c void OnClick (DialogiNterface dialog, int whichbutton) {settitle ("Click Button3 on the dialog box");  
        }  
                });  Builder.create (). Show ();  Build Alertdialog, and show}

From the class name it can be seen that this is a builder mode, through the builder object to assemble the various parts of the dialog, such as: Title\button\message, and so on, will dialog the construction and representation of the separation.

The result is as shown in the figure:

(2) Alertdialog

Alertdialog public class Alertdialog extends Appcompatdialog implements Dialoginterface {//Controller, accept Buil  

    The individual parameters in der member variable P are private Alertcontroller malert;  
    Constructor protected Alertdialog (context context, int theme) {This (context, theme, true); }//Construct Alertdialog Alertdialog (context context, int theme, Boolean createcontextwrapper) {Super (CO  
        ntext, Resolvedialogtheme (context, theme), createcontextwrapper);  
        Mwindow.alwaysreadcloseontouchattr ();  
    Malert = new Alertcontroller (GetContext (), this, GetWindow ()); }//is actually called the Settitle method of the Malert @Override public void Settitle (charsequence title) {Super.sett  
        Itle (title);  
    Malert.settitle (title); }//is actually called the Setcustomtitle method of Malert public void Setcustomtitle (View customtitleview) {MALERT.SETCU  
    Stomtitle (Customtitleview);  
    } public void Setmessage (Charsequence message) {    Malert.setmessage (message); }//Alertdialog other code omitted//************ builder for Alertdialog internal class ******************* public static C  
        Lass Builder {//1: Stores various parameters of the Alertdialog, such as title, Message, icon, and so on.  
        Private final Alertcontroller.alertparams P;  
        Property omits public Builder (context context) {This (context, resolvedialogtheme (context, 0)); } public Builder (context context, int theme) {P = new Alertcontroller.alertparams (New context  
            Themewrapper (Context, Resolvedialogtheme (context, theme));  
        Mtheme = theme;  
            }//other code of Builder omitted ...//2: Set various parameters public Builder Settitle (charsequence title) {  
            P.mtitle = title; Ret

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.