1.静态工厂方法代替构造器
静态工厂方法与构造器的区别
优点
- 静态工厂方法与构造器方法优势在于:有名称
- 不必在每次调用时都创建一个对象
- 可以返回原返回类型的任何子类型的对象
- 可以有多个参数相同但名称不同的工厂方法
- 可以减少对外暴露的属性
多了一层控制,方便统一修改,常用于编写测试用例
Class Person { public static Person getInstance(){ return new Person(); // 这里可以改为 return new Player() / Cooker() } } Class Player extends Person{ } Class Cooker extends Person{ }
public class t1 { String name; private t1(){
} public static t1 newT1(){ t1 t = new t1(); t.name = "t"; return t; } public static t1 newT2(){ t1 t = new t1(); t.name = "t1"; return t; }
}
缺点
- 如果类中不含公有的或者受保护的构造器,就不能被子类化。即如果含有private的构造器,该类不能被继承
- 与其他的静态方法实际上没有任何区别
2.Builder模式(构建器模式)
构建器模式既能保证安全也能保证可读
常用于类的构造器或者静态工厂中具有多个参数的情形
public class T {
private int a;
private int b;
private int c;
public static class Builder{
private int a;
private int b;
private int c;
public Builder(){}
public Builder seta(int a){
this.a = a;
return this;
}
public Builder setb(int b){
this.b = b;
return this;
}
public Builder setc(int c){
this.c = c;
return this;
}
public T build(){
return new T(this);
}
}
private T(Builder builder){
a = builder.a;
b = builder.b;
c = builder.c;
}
public static void main(String[] args){
T t = new T.Builder().seta(0).setb(1).setc(2).build();
}
}