建造者模式(Builder)

使用场景:如果一个类的构造需要很多参数,但这些参数又不都是必须的。

Android开发中经常使用的例子

new AlertDialog.Builder(this)
   .setTitle("Design Patterns")
   .setMessage("Builder is awesome")
   .create();

实践

  1. 假如一个User类定义如下
public class User {
   private String firstName;
   private String lastName;
   private int age;
}
  1. 若想使用如下方法构建
new User.Builder()
   .setFirstName("Leonardo")
   .setLastName("da Vinci")
   .setAge(67)
   .create();
  1. 内部构建一个Builder类
static class Builder {
   private String firstName;
   private String lastName;
   private int age;
 
   public Builder setFirstName(final String firstName) {
      this.firstName = firstName;
      return this;
   }
 
   public Builder setLastName(final String lastName) {
      this.lastName = lastName;
      return this;
   }
 
   public Builder setAge(final int age) {
      this.age = age;
      return this;
   }
 
   public User create() {
      return new User(this);
   }
}

  1. User类修改为
public class User {
   private String firstName;
   private String lastName;
   private int age;
 
   private User(final Builder builder) {
        firstName = builder.firstName;
        lastName = builder.lastName;
        age = builder.age;
   }
}

参考

  • Design Patterns in Android  –  Builder

你可能感兴趣的:(建造者模式(Builder))