Ubiquitous Design Pattern in Android development-Builder Pattern

Source: Internet
Author: User
Tags eventbus

Ubiquitous Design Pattern in Android development-Builder Pattern

 

So what is the Builder mode. By searching, you will find that most of the definitions on the Internet are

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

But after reading this definition, there is nothing to use. You still don't know what the Builder design mode is. My personal attitude here is to learn the design pattern and do not care too much about its definition. The definition is often abstract. The best example of learning it is through the sample code.

Let's use an example to introduce the Builder mode. Assume that there is a Person class. We use this Person class to construct a large number of people. This Person class has many attributes, such as name, age, weight, and height, in addition, these values are not set, that is, null is allowed. The definition of this class is as follows.

public class Person {    private String name;    private int age;    private double height;    private double weight;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        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;    }}

Then we may define a constructor for convenience.

    public Person(String name, int age, double height, double weight) {        this.name = name;        this.age = age;        this.height = height;        this.weight = weight;    }

For the convenience of the new object, you may also define an empty constructor.

    public Person() {    }

Even if you are too lazy to pass some parameters, you will define the following constructor.

  public Person(String name) {        this.name = name;    }    public Person(String name, int age) {        this.name = name;        this.age = age;    }    public Person(String name, int age, double height) {        this.name = name;        this.age = age;        this.height = height;    }

Then you can create various required objects.

Person p1 = new Person (); Person p2 = new Person (Zhang San); Person p3 = new Person (Li Si, 18); Person p4 = new Person (Wang Wu, 21,180 ); person p5 = new Person (Zhao Liu, 17,170, 65.4 );

You can imagine the disadvantage of this creation. The most intuitive thing is what the last two parameters of the constructor of the four parameters mean and the readability is not very good. If you do not click to view the source code, the ghost knows which is weight and which is height. Another problem is that when there are many parameters, writing this constructor will be very troublesome. At this time, if you change the angle, try the Builder mode, you will find that the code is readable at once.

We add a static internal class Builder class to the Person class and modify the constructor of the Person class. The Code is as follows.

public class Person {    private String name;    private int age;    private double height;    private double weight;    privatePerson(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 age) {        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 name(String name){            this.name=name;            return this;        }        public Builder age(int age){            this.age=age;            return this;        }        public Builder height(double height){            this.height=height;            return this;        }        public Builder weight(double weight){            this.weight=weight;            return this;        }        public Person build(){            return new Person(this);        }    }}

From the code above, we can see that we have defined a variable identical to the Person class in the Builder class, and set the attribute value through a series of member functions, but the returned values are all this, that is, they are all Builder objects. Finally, a build function is provided to create the Person object. The Person object is returned, and the corresponding constructor is defined in the Person class, that is, the input parameter of the constructor is the Builder object, and then assigns values to its member variables in turn. The corresponding values are the values in the Builder object. In addition, the member function in the Builder class returns the Builder object. Another function is to make it support chain calls, greatly enhancing the code readability.

So we can create the Person class in this way.

Person. builder builder = new Person. builder (); Person person = builder. name (James ). age (18 ). the height (178.5 ). weight (1, 67.4 ). build ();

Do you think the creation process becomes so clear at once. The corresponding values are clearly visible and the readability is greatly enhanced.

In fact, in Android, the Builder mode is also widely used. For example, Common Dialog Box Creation

AlertDialog. builder builder = new AlertDialog. builder (this); AlertDialog dialog = builder. setTitle ). setIcon (android. r. drawable. ic_dialog_alert ). setView (R. layout. myview ). setPositiveButton (R. string. positive, new DialogInterface. onClickListener () {@ Override public void onClick (DialogInterface dialog, int which ){}}). setNegativeButton (R. string. negative, new DialogInterface. onClickListener () {@ Override public void onClick (DialogInterface dialog, int which ){}}). create (); dialog. show ();

In fact, two common classes in java are also the Builder mode, namely StringBuilder and StringBuffer, but the implementation process is simplified.

Let's look for the application of the Builder model in various frameworks.

For example, GsonBuilder in Gson does not post the code because the code is too long. If you are interested, go to the source code and paste the usage of its Builder here.

GsonBuilder builder=new GsonBuilder();Gson gson=builder.setPrettyPrinting()        .disableHtmlEscaping()        .generateNonExecutableJson()        .serializeNulls()        .create();

There is also a Builder in EventBus, but this Builder cannot be accessed externally, because its constructor is not public, but you can see its application in the EventBus class.

public static EventBusBuilder builder() {    return new EventBusBuilder();}public EventBus() {    this(DEFAULT_BUILDER);}EventBus(EventBusBuilder builder) {    subscriptionsByEventType = new HashMap
  
   , CopyOnWriteArrayList
   
    >();    typesBySubscriber = new HashMap
    
     >>();    stickyEvents = new ConcurrentHashMap
     
      , Object>();    mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);    backgroundPoster = new BackgroundPoster(this);    asyncPoster = new AsyncPoster(this);    subscriberMethodFinder = new SubscriberMethodFinder(builder.skipMethodVerificationForClasses);    logSubscriberExceptions = builder.logSubscriberExceptions;    logNoSubscriberMessages = builder.logNoSubscriberMessages;    sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;    sendNoSubscriberEvent = builder.sendNoSubscriberEvent;    throwSubscriberException = builder.throwSubscriberException;    eventInheritance = builder.eventInheritance;    executorService = builder.executorService;}
     
    
   
  

Let's take a look at the famous network request framework OkHttp

Request.Builder builder=new Request.Builder();Request request=builder.addHeader(,)    .url()    .post(body)    .build();

In addition to the Request, Response is also created in Builder mode. Paste the Response Constructor

  private Response(Builder builder) {    this.request = builder.request;    this.protocol = builder.protocol;    this.code = builder.code;    this.message = builder.message;    this.handshake = builder.handshake;    this.headers = builder.headers.build();    this.body = builder.body;    this.networkResponse = builder.networkResponse;    this.cacheResponse = builder.cacheResponse;    this.priorResponse = builder.priorResponse;  }

It can be seen that the Builder mode is widely used in various frameworks. Summary

Defines a static internal class Builder. The internal member variables are the same as the external class. The Builder class is used to assign values to member variables through a series of methods and returns the current object (this) the Builder class provides a build method or create method for creating the corresponding external class. This method internally calls a private constructor of the external class, the parameter of this constructor is the internal class Builder external class which provides a private constructor for internal class calls. In this constructor, the value of the member variable is assigned, and the value is the value corresponding to the Builder object.

 

Related Article

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.