[Builder Pattern] 建造者模式

2016-07-19  本文已影响0人  Sinexs

What does Builder Pattern looks like

In Material-Dialog

new MaterialDialog.Builder(this) 
             .title(R.string.title) 
             .content(R.string.content) 
             .positiveText(R.string.agree) 
             .negativeText(R.string.disagree) 
             .show();

In OkHttp

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

Also see in Android Source Code - AlertDialog, Notification...

What is Builder Pattern

The builder pattern is an object creation software design pattern.
首先,建造者(生成器)模式是一种构建对象的设计模式。

When use Builder Pattern

When would you use the Builder Pattern? [closed]

The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

一般的构造方法

Pizza(int size) { ... } Pizza(int size, boolean cheese) { ... } 
Pizza(int size, boolean cheese, boolean pepperoni) { ... } 
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

The better alternative is to use the Builder Pattern.

How to use Builder Pattern

public class Pizza { 
  private int size; 
  private boolean cheese; 
  private boolean pepperoni; 
  private boolean bacon; 

  private Pizza(Builder builder) { 
    size = builder.size; 
    cheese = builder.cheese; 
    pepperoni = builder.pepperoni; 
    bacon = builder.bacon; 
  }

  public static class Builder { 
    //required 
    private final int size; 
  
    //optional 
    private boolean cheese = false; 
    private boolean pepperoni = false; 
    private boolean bacon = false; 

    public Builder(int size) { 
      this.size = size; 
    } 

    public Builder cheese(boolean value) { 
      cheese = value; 
      return this; 
    } 

    public Builder pepperoni(boolean value) { 
      pepperoni = value; 
      return this; 
    } 

    public Builder bacon(boolean value) { 
      bacon = value; 
      return this; 
   } 

    public Pizza build() { 
      return new Pizza(this); 
    } 

  } 
}
Pizza pizza = new Pizza.Builder(12)
            .cheese(true) 
            .pepperoni(true) 
            .bacon(true) 
            .build();

Conclusion

Reference

上一篇 下一篇

猜你喜欢

热点阅读