构建者设计模式
兄弟们好,今天我们来聊一下构建者设计模式。
这个设计模式你一定见到过,可能只是它认识你而你不认识它而已,我们在学习StringBuilder
的时候有没有见过append
的链式编程,还有在使用Mybatis
,zookeeper
,线程池等等框架的时候,是不是经常会看到如下的代码
new FactoryBuilder()
.setName()
.setFactory()
.setOwner()
.build();
是不是当时感觉这么写代码贼爽,比我们动不动就是一行一个set
来的舒服的多,没错这个就是我们今天的主题「构建者设计模式」
先看类图,再看代码
「类图实现」
「代码实现:在构建者中声明相同的字段实现(省略了外部的get方法)」
代码语言:javascript复制class Person{
private String name ;
private Integer age ;
private Double money ;
private String phone ;
private String city ;
public Person(String name, Integer age, Double money, String phone, String city) {
this.name = name;
this.age = age;
this.money = money;
this.phone = phone;
this.city = city;
}
public static class Builder{
private String name ;
private Integer age ;
private Double money ;
private String phone ;
private String city ;
public Builder setName(String name) {
this.name = name;
return this ;
}
public Builder setAge(Integer age) {
this.age = age;
return this ;
}
public Builder setMoney(Double money) {
this.money = money;
return this ;
}
public Builder setPhone(String phone) {
this.phone = phone;
return this ;
}
public Builder setCity(String city) {
this.city = city;
return this ;
}
public Person build(){
return new Person(this.name,this.age,this.money,this.phone,this.city);
}
}
}
「代码实现:在构建者中直接创建对象,不声明字段」
代码语言:javascript复制class Person1{
private String name ;
private Integer age ;
private Double money ;
private String phone ;
private String city ;
public static class Builder{
private Person1 person1 = new Person1();
public Builder setName(String name) {
person1.name = name;
return this ;
}
public Builder setAge(Integer age) {
person1.age = age;
return this ;
}
public Builder setMoney(Double money) {
person1.money = money;
return this ;
}
public Builder setPhone(String phone) {
person1.phone = phone;
return this ;
}
public Builder setCity(String city) {
person1.city = city;
return this ;
}
public Person1 build(){
return person1 ;
}
}
}
「测试代码:」
代码语言:javascript复制public static void main(String[] args) {
Person person = new Person.Builder()
.setAge(18)
.setCity("武汉").setPhone("10086").build();
}
今天的设计模式到这里就结束了,兄弟们,晚安呀。