Separate the construction of a complex object from its representation so that the same construction process an create different representations.
意思就是:讲一个复杂对象的构建与它的表示分离,使得同样的构造过程可以创建不同的描述。
建造者一般有以下四个角色:
工厂模式 | 构造者模式 | |
---|---|---|
关注点 | 构造出实际类对象 | 构造方式类型、构建顺序 等不同产生的类的实例对象不同,着重过程 |
类图
实现
public class Bread {
private String breadType;
public String getBreadType() {
return breadType;
}
public void setBreadType(String breadType) {
this.breadType = breadType;
}
}
public class Sandwich {
private String sandwich;
private int count;
public String getSandwich() {
return sandwich;
}
public void setSandwich(String sandwich) {
this.sandwich = sandwich;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
public class Sauce {
private String sauce;
public String getSauce() {
return sauce;
}
public void setSauce(String sauce) {
this.sauce = sauce;
}
}
public class Hamburger {
private Bread bread;
private Sauce sauce;
private Sandwich sandwich;
public Bread getBread() {
return bread;
}
public void setBread(Bread bread) {
this.bread = bread;
}
public Sauce getSauce() {
return sauce;
}
public void setSauce(Sauce sauce) {
this.sauce = sauce;
}
public Sandwich getSandwich() {
return sandwich;
}
public void setSandwich(Sandwich sandwich) {
this.sandwich = sandwich;
}
}
public interface HamburgerBuilder {
void buildBread(String bread);
void buildSandwich(String sandwich, int count);
void buildSauce(String sauce);
Hamburger build();
}
public class HamburgerBuilderImpl implements HamburgerBuilder {
private Hamburger hamburger = new Hamburger();
@Override
public void buildBread(String breadType) {
Bread bread = new Bread();
bread.setBreadType(breadType);
hamburger.setBread(bread);
}
@Override
public void buildSandwich(String sandwichName, int count) {
Sandwich sandwich = new Sandwich();
sandwich.setSandwich(sandwichName);
sandwich.setCount(count);
hamburger.setSandwich(sandwich);
}
@Override
public void buildSauce(String sauceName) {
Sauce sauce = new Sauce();
sauce.setSauce(sauceName);
hamburger.setSauce(sauce);
}
@Override
public Hamburger build() {
System.out.println("构建了一个:"
+ hamburger.getSandwich().getCount() + "层" + hamburger.getSandwich().getSandwich()
+ hamburger.getSauce().getSauce()
+ hamburger.getBread().getBreadType()
+ "汉堡");
return hamburger;
}
}
public class Client {
public static void main(String[] args) {
HamburgerBuilder builder = new HamburgerBuilderImpl();
builder.buildBread("燕麦");
builder.buildSandwich("猪排", 2);
builder.buildSauce("芝士");
//此时就构建了一个双层猪排芝士汉堡
Hamburger hamburger = builder.build();
}
}
执行结果如下,此时一个双层猪排芝士燕麦汉堡就构建好了,只要出入不同的夹层如鸡排那就是鸡扒汉堡。