建造者模式
✅ 建造者模式用于构建复杂的不可变的对象
其实上面这句话就是建造者模式的灵魂,复杂的对象,例如拥有很多成员变量的类,我们假设让它不可变,我们需要声明变量属性是final的,并且我们需要用多个构造函数去设置这些变量值,例如
/**
* Created by cuishifeng on 2018/5/31.
*/
public class Food {
private final String apple;
private final String banana;
private final String pear;
private final String grape;
public Food(String apple){
this(apple,"");
}
public Food(String apple,String banana){
this(apple,banana,"");
}
public Food(String apple,String banana,String pear){
this(apple,banana,pear,"");
}
public Food(String apple,String banana,String pear,String grape){
this.apple =apple;
this.banana = banana;
this.pear = pear;
this.grape = grape;
}
}
建立一个只需要所需属性作为参数的构造函数,为类的成员变量赋值,这样可以创建一个不可变类,但是对于成员变量很多的时候,这样的劣势就会凸显,我们需要建立各种各样的构造函数去满足需求。
用getter、setter
我们遵循javaBeans约定,有一个无参构造函数,每个成员变量都有对应的getter和setter方法
/**
* Created by cuishifeng on 2018/5/31.
*/
public class Food2 {
private String apple;
private String banana;
private String pear;
private String grape;
public String getApple() {
return apple;
}
public void setApple(String apple) {
this.apple = apple;
}
public String getBanana() {
return banana;
}
public void setBanana(String banana) {
this.banana = banana;
}
public String getPear() {
return pear;
}
public void setPear(String pear) {
this.pear = pear;
}
public String getGrape() {
return grape;
}
}
使用这种方式对象是一直都处于可变状态,无论我们实例化对象后任何时候调用setter方法都可以改变这个对象