建造者模式的主要特征是,通过一步一步的方式生成一些东西。每个生成的东西,即使其中的任何一步都不相同,但也将遵循同样的过程。
4个角色:指挥者(Director),建造者(Builder),具体建造者(ConcreteBuilder),产品(Product)
产品:需要创建的对象产品
建造者:本质为抽象类,里面的抽象方法供具体建造者重写,声明产品的引用
具体建造者:创建产品的实例并且实现建造者多个方法对产品进行装配
指挥者:调用建造者抽象类以及其方法
代码:
// produce to be built
class
Starbucks {
private
String size;
private
String drink;
public
void
setSize(String size) {
this
.size = size;
}
public
void
setDrink(String drink) {
this
.drink = drink;
}
}
//abstract builder
abstract
class
StarbucksBuilder {
protected
Starbucks starbucks;
public
Starbucks getStarbucks() {
return
starbucks;
}
public
void
createStarbucks() {
starbucks =
new
Starbucks();
System.out.println(
"a drink is created"
);
}
public
abstract
void
buildSize();
public
abstract
void
buildDrink();
}
// Concrete Builder to build tea
class
TeaBuilder
extends
StarbucksBuilder {
public
void
buildSize() {
starbucks.setSize(
"large"
);
System.out.println(
"build large size"
);
}
public
void
buildDrink() {
starbucks.setDrink(
"tea"
);
System.out.println(
"build tea"
);
}
}
// Concrete builder to build coffee
class
CoffeeBuilder
extends
StarbucksBuilder {
public
void
buildSize() {
starbucks.setSize(
"medium"
);
System.out.println(
"build medium size"
);
}
public
void
buildDrink() {
starbucks.setDrink(
"coffee"
);
System.out.println(
"build coffee"
);
}
}
//director to encapsulate the builder
class
Waiter {
private
StarbucksBuilder starbucksBuilder;
public
void
setStarbucksBuilder(StarbucksBuilder builder) {
starbucksBuilder = builder;
}
public
Starbucks getstarbucksDrink() {
return
starbucksBuilder.getStarbucks();
}
public
void
constructStarbucks() {
starbucksBuilder.createStarbucks();
starbucksBuilder.buildDrink();
starbucksBuilder.buildSize();
}
}
//customer
public
class
Customer {
public
static
void
main(String[] args) {
Waiter waiter =
new
Waiter();
StarbucksBuilder coffeeBuilder =
new
CoffeeBuilder();
//Alternatively you can use tea builder to build a tea
//StarbucksBuilder teaBuilder = new TeaBuilder();
waiter.setStarbucksBuilder(coffeeBuilder);
waiter.constructStarbucks();
//get the drink built
Starbucks drink = waiter.getstarbucksDrink();
}
}