[DesignPattern]Builder Design Pattern

Keywords: Java Android

Definition of pattern

Separate the construction of a complex object from its representation, so that the same construction process can create different representations.

Usage scenarios of patterns

  1. The same method, different execution order, and different event results;
  2. Multiple components or parts can be assembled into one object, but the results are not the same;
  3. The product class is very complex, or the call order in the product class has different performance, so it is very suitable to use the builder mode at this time;

Pattern implementation in Android source code

In Android source code, the most commonly used Builder mode is AlertDialog.Builder, which is used to build complex AlertDialog objects. A simple example is as follows:

//Show basic AlertDialog 
private void showDialog(Context context) {  
        AlertDialog.Builder builder = new AlertDialog.Builder(context);  
        builder.setIcon(R.drawable.icon);  
        builder.setTitle("Title");  
        builder.setMessage("Message");  
        builder.setPositiveButton("Button1",  
                new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int whichButton) {  
                        setTitle("Click on the Button1");  
                    }  
                });  
        builder.setNeutralButton("Button2",  
                new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int whichButton) {  
                        setTitle("Click on the Button2");  
                    }  
                });  
        builder.setNegativeButton("Button3",  
                new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int whichButton) {  
                        setTitle("Click on the Button3");  
                    }  
                });  
        builder.create().show();  // structure AlertDialog, And display
    } 

 

 

Advantages and disadvantages

Advantage

  • Good encapsulation, the use of builder mode can make the client do not have to know the details of the internal composition of the product;
  • Independent builder, easy to expand;
  • Some other objects in the system will be used in the process of object creation, which are not easy to get in the process of product object creation.

shortcoming

  • Redundant Builder objects and Director objects will be generated and memory will be consumed;
  • The object's construction process is exposed.

Link: https://www.jianshu.com/p/87288925ee1f

Posted by suttercain on Tue, 03 Dec 2019 19:10:13 -0800