设计模式-构造者模式

构造者模式
软件系统,复杂对象的创建工作,各个部分的子对象用一定的算法构成,需求变化,
复杂对象的各个部分经常面临剧烈的变化,但是组合在一起的算法相对稳定/一些基本部件不变,
其组合经常变化的时候/变与不变分离
场景:
Coffee 实际需要的产品
制作拿铁咖啡,拿铁咖啡的有下面几种构成:咖啡名称,咖啡浓缩度,热牛奶量,奶泡量
Public class coffee{ private string name;private int espressos;private int hotmilk;private int milkFoam}
Builder 制作咖啡过程的抽象
制作咖啡需要分为以下几步:咖啡名字,制作浓缩 Espresso,制作热牛奶,制作奶泡
public abstract class Bulider{
public abstract void buildName(string name);
public abstract void buildespressos(int espressos);
public abstract void buildhotmilk(int hotmilk);
public abstract void buildmilklFoam(int milkFoam);
public abstract Coffee build();}
CoffeeBuilder 具体制作咖啡过程
public class CoffeeBuilder extends Builder{
private Coffee mcoffee;
public CoffeeBuilder(mcoffee = new Coffee;);
public void buildName(string name){mcoffee.setName(name)};…}
public Coffee build(){return mcoffee;}
CoffeeShopWaiter 使用咖啡制作过程生产咖啡
public class ShopWaiter{
private CoffeeBuilder mcoffeebuilder;
public void setCoffeeBuilder(CoffeeBuilder coffeebuilder){mcoffeebuilder = coffeebuilder};
public Coffee makeCoffee(string name,int espressos,int hotmilk,int milkFoam) {mcoffeebuilder.buildName(name)};…;
return mcoffeebuilder.build();}
消费过程
CoffeeShopWaiter coffeeShopWaiter = new CoffeeShopWaiter();
CoffeeBuilder coffeeBuilder = new CoffeeBuilder();
coffeeShopWaiter.setCoffeeBuilder(coffeeBuilder);
Coffee coffee = coffeeShopWaiter.makeCoffee(“拿铁”, 50, 150, 50);

你可能感兴趣的:(设计模式)