Android设计模式-Builder

public class Person {
 private String name;
 private int age;
 private int height;
 private int width;
 private Person(Builder builder) {
  this.name = builder.name;
  this.age = builder.age;
  this.height = builder.height;
  this.width = builder.width;
 }
 public static class Builder {
  private String name;
  private int age;
  private int height;
  private int width;
  public Builder setName(String name) {
   this.name = name;
   return this;
  }
  public Builder setAge(int age) {
   this.age = age;
   return this;
  }
  public Builder setHeight(int height) {
   this.height = height;
   return this;
  }
  public Builder setWidth(int width) {
   this.width = width;
   return this;
  }
  public Person show() {
   Person person = new Person(this);
   return person;
  }
 }
}

 

   测试

public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Person mPerson = new Person.Builder()
    .setName("张三")
    .setAge(12)
    .setWidth(13)
    .setHeight(50)
    .show();
 }
}

    

Android AlerDialog 就是一个 Builder设计模式.

new AlertDialog.Builder(...).setTitle("")... ...show();

 

优点与缺点

优点 :

1、良好的封装性, 使用建造者模式可以使客户端不必知道产品内部组成的细节;

2、建造者独立,容易扩展;

3、 在对象创建过程中会使用到系统中的一些其它对象,这些对象在产品对象的创建过程中不易得到。

缺点 :

1、会产生多余的Builder对象以及Director对象,消耗内存;

2、对象的构建过程暴露。

你可能感兴趣的:(Android设计模式-Builder)