建造者模式是设计模式的一种,将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
实用范围
1 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。[1]
2 当构造过程必须允许被构造的对象有不同表示时。
介绍都是cp来的,直接上代码,建造者模式主要就是方便对对象的创建,管理,可以对对象中的field进行加工处理,在参数接收传递过程中是比较方便的~
package com.study.day;
/**
* 建造者模式
*/
public class Desk {
private String name;
private Integer height;
private Integer width;
private String price;
public Desk(Builder builder) {
this.name = builder.name;
this.height = builder.height;
this.width = builder.width;
this.price = builder.price;
}
public static Builder builder(){
return new Builder();
}
public static class Builder{
private String name;
private Integer height;
private Integer width;
private String price;
public Builder name(String name){
this.name = name;
return this;
}
public Builder height(Integer height){
this.height = height;
return this;
}
public Builder width(Integer width){
this.width = width;
return this;
}
public Builder price(String price){
this.price = price;
return this;
}
public Desk build(){
return new Desk(this);
}
}
@Override
public String toString() {
return "{" +
"name='" + name + '\'' +
", height=" + height +
", width=" + width +
", price='" + price + '\'' +
'}';
}
}
下面简单的调用下~
package com.study.day;
import sun.security.krb5.internal.crypto.Des;
public class DeskMain {
public static void main(String[] args) {
Desk desk = Desk.builder()
.name("方桌")
.height(130)
.width(100)
.price("100元")
.build();
System.out.println("构造的桌子:"+desk.toString());
}
}
结果: