其他设计模式
java单例模式
java建造者模式
java策略模式
java代理模式
java观察者模式
java适配器模式
java外观模式
使用场景
遇到多个构造器参数时要考虑用构造器
实现
不直接生产想要的对象,而是让客户端利用所以必要的参数调用构造器,得到一个builder对象,最后,客户端调用无参的build方法来生产不可变的对象,这个bulider是它构建的类的静态成员类
public class Student {
private final String name;
private final int age;
private final int height;
private final int sex;
private final String schoolName;
private final String profession;
public static class Builder {
private final String name;
private final int age;
private int height;
private int sex;
private String schoolName;
private String profession;
public Builder(String name, int age) {
this.name = name;
this.age = age;
}
public Builder height(int val) {
height = val;
return this;
}
public Builder sex(int val) {
sex = val;
return this;
}
public Builder schoolName(String val) {
this.schoolName = val;
return this;
}
public Builder sprofession(String val) {
profession = val;
return this;
}
// 构造器入口
public Student build() {
return new Student(this);
}
}
private Student(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.height = builder.height;
this.sex = builder.sex;
this.schoolName = builder.schoolName;
this.profession = builder.profession;
}
}
注意Sutdent是不可变的,所有的默认参数值都单独放在一个地方,builder的setter方法返回builder本身,以便可以把调用链接起来,下面就是客户端代码:
Student jack=new Student.Builder("jack",20).height(173).schoolName("Harvard ").build();
Student lucy=new Student.Builder("lucy",21).height(163).sex(1).schoolName("Harvard ").build();
上述代码name和age是作为必需参数,故放在builder的构造器参数中, 如果都是可选参数,就都可以参照height,sex等参数的写法
网友评论