1,拒绝类被继承
2,拒绝外部对类的实例化,强制调用构建()创建类的对象
public class CarFactory {
private final int type;
private String name;
private int cost;
public static class Builder {
private final int type;
private String name;
private int cost;
public Builder(int type) {
this.type = type;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setCost(int cost) {
this.cost = cost;
return this;
}
public CarFactory build() {
return new CarFactory(this);
}
}
private CarFactory(Builder builder) {
this.type = builder.type;
this.name = builder.name;
this.cost = builder.cost;
}
}
CarFactory类不可以被继承,会提示如下错误:
Implicit super constructor CarFactory() is undefined for default constructor. Must define an explicit constructor
扩展:
静态内部类:建造者
当CarFactory初始化时有大量参数,推荐使用生成器实例化CarFactory类。而不是使用CarFactory公有构造函数携带大量入参来完成初始化。
CarFactory car = new CarFactory.Builder(0).setCost(10000).setName("奥拓").build();
这种实例化方式增强了代码可读性,并且在初始化参数时可以防止注入参数错误的问题。