设计模式-建造者模式
class MilkTea {
double price;
String topping = "cream";
String tea = "Common tea";
Integer suger = 100;
public MilkTea() {
this.price = 9.9;
}
public double getPrice() {
return this.price;
}
}
class LatteMilkTea extends MilkTea {
public LatteMilkTea() {
this.price = 10.9;
}
}
class IceCreamMilkTea extends MilkTea {
public IceCreamMilkTea() {
this.price = 11.9;
}
}
interface MilkteaBuilder {
void reset();
void addTopping();
void addTea();
void addSugerLevel();
MilkTea getProduct();
}
class LatteMilkTeaBuilder implements MilkteaBuilder {
private LatteMilkTea latteMilkTea;
@Override
public void reset() {
this.latteMilkTea = new LatteMilkTea();
}
@Override
public void addTopping() {
latteMilkTea.topping = "latte topping";
}
@Override
public void addTea() {
latteMilkTea.tea = "latte tea";
}
@Override
public void addSugerLevel() {
latteMilkTea.suger = 95;
}
@Override
public MilkTea getProduct() {
System.out.format("LatteMilkTea: %s %s %s\n", this.latteMilkTea.topping, this.latteMilkTea.tea, this.latteMilkTea.price);
return this.latteMilkTea;
}
}
class IceCreamMilkTeaBuilder implements MilkteaBuilder {
private IceCreamMilkTea iceCreamMilkTea;
@Override
public void reset() {
this.iceCreamMilkTea = new IceCreamMilkTea();
}
@Override
public void addTopping() {
iceCreamMilkTea.topping = "ice cream topping";
}
@Override
public void addTea() {
iceCreamMilkTea.tea = "ice cream tea";
}
@Override
public void addSugerLevel() {
iceCreamMilkTea.suger = 95;
}
@Override
public MilkTea getProduct() {
System.out.format("LatteMilkTea: %s %s %s\n", this.iceCreamMilkTea.topping, this.iceCreamMilkTea.tea, this.iceCreamMilkTea.price);
return this.iceCreamMilkTea;
}
}
class MilkTeaDirector {
private MilkteaBuilder milkteaBuilder;
public MilkTeaDirector(MilkteaBuilder milkteaBuilder) {
this.milkteaBuilder = milkteaBuilder;
}
public void changeBuiler(MilkteaBuilder milkteaBuilder) {
this.milkteaBuilder = milkteaBuilder;
}
public MilkTea makeMikeTea() {
this.milkteaBuilder.reset();
this.milkteaBuilder.addTopping();
this.milkteaBuilder.addTea();
this.milkteaBuilder.addSugerLevel();
return this.milkteaBuilder.getProduct();
}
public MilkTea make(String type) {
if ("Latte".equals(type)) {
this.changeBuiler(new LatteMilkTeaBuilder());
} else if ("IceCream".equals(type)) {
this.changeBuiler(new IceCreamMilkTeaBuilder());
}
return this.makeMikeTea();
}
}
public class MilkTeaShop {
public static void main(String[] args) {
MilkTeaDirector director = new MilkTeaDirector(new LatteMilkTeaBuilder());
director.makeMikeTea();
director.changeBuiler(new IceCreamMilkTeaBuilder());
director.makeMikeTea();
director.make("Latte");
director.make("IceCream");
}
}