建造者模式(Builder): 使用多个简单的对象一步一步构建成一个复杂的对象。这种类型的设计模式属于创建型模式,提供一种创建对象的最佳方式。
应用:
比如坑德基的汉堡、薯条、可乐、鸡翅是不变的,但是套餐是经常变化的
Java 中的 StringBuilder
如何使用: 一些基本部件不变,而其组合经常变化
与工厂模式的不同:建造者关注零件的组装过程,而工厂方法模式更关注零件的创建过程
建造者组成: 产品、抽象建造者、具体建造者、指挥者 4 个要素组成
例如:
【产品】装修一套房子:沙发、灯、浴室、地板
【指挥者】 Leader 指挥工人装修
【具体的建造者】工人
public class Room { //沙发
private String sofa;
//灯
private String light;
//浴室
private String bashroom;
//地板
private String floor; public String getSofa() {
return sofa;
} public void setSofa(String sofa) {
this.sofa = sofa;
} public String getLight() {
return light;
} public void setLight(String light) {
this.light = light;
} public String getBashroom() {
return bashroom;
} public void setBashroom(String bashroom) {
this.bashroom = bashroom;
} public String getFloor() {
return floor;
} public void setFloor(String floor) {
this.floor = floor;
} @Override
public String toString() {
return "Room{" +
"sofa='" + sofa + '\'' +
", light='" + light + '\'' +
", bashroom='" + bashroom + '\'' +
", floor='" + floor + '\'' +
'}';
}
}
public abstract class Builder { //计划装修房子
protected Room room = new Room();
public abstract void buildSofa();
public abstract void buildLight();
public abstract void buildBashRoom();
public abstract void buildFloor(); public Room getResult(){
return room;
} }
public class WorkerBuilder extends Builder{
@Override
public void buildSofa() {
room.setSofa("香港皇家沙发");
System.out.println("装修:香港皇家沙发");
} @Override
public void buildLight() {
room.setLight("德州进口灯");
System.out.println("装修:德州进口灯");
} @Override
public void buildBashRoom() {
room.setBashroom("伊丽莎白同款浴室");
System.out.println("装修:伊丽莎白同款浴室");
} @Override
public void buildFloor() {
room.setFloor("天空绚烂地板");
System.out.println("装修:天空绚烂地板");
}
}
public class Leader { protected Builder builder; public Leader(Builder builder){
this.builder = builder;
} public Room construct(){
builder.buildBashRoom();
builder.buildFloor();
builder.buildLight();
builder.buildSofa();
return builder.getResult();
}
}
public class Client {
public static void main(String []args){
Builder builder = new WorkerBuilder();
Leader leader = new Leader(builder);
Room newRoom = leader.construct();
System.out.println(newRoom);
}
}