1、基本概念
建造者模式适用于一步一步创建复杂对象的过程。
复杂对象的各个部分经常面临着剧烈的变化,但是将它们组合在一起的方式却相对稳定
2、类图和角色
角色:
抽象建造者(指挥者)
具体建造者
具体产品
3、案例
例如:去肯德基店去点餐,有不同的套餐产生不同的订单
案例:
类图:
抽象建造者IorderBulider :
public interface IorderBulider { void addHamburger(String name); void addCoke(String name); void addChicken(String name); void addFruitjuice(String name); Order buildOrder(); }
具体的建造者OrderBuilder :
public class OrderBuilder implements IorderBulider { Order order = new Order(); @Override public void addHamburger(String name) { order.setHamburger(name); } @Override public void addCoke(String name) { order.setCoke(name); } @Override public void addChicken(String name) { order.setChicken(name); } @Override public void addFruitjuice(String name) { order.setFruitjuice(name); } @Override public Order buildOrder(){ return order; } }
具体产品Order :
@Data public class Order { private String hamburger; private String coke; private String chicken; private String fruitjuice; }
测试:
public class Test { public static void main(String[] args) { IorderBulider iorderBulider = new OrderBuilder(); iorderBulider.addChicken("韩式炸鸡"); iorderBulider.addCoke("百事可乐"); iorderBulider.addHamburger("德式汉堡"); Order order = iorderBulider.buildOrder(); System.out.println(order); } }
链式写法:
public class OrderBuilder implements IorderBulider { Order order = new Order(); @Override public IorderBulider addHamburger(String name) { order.setHamburger(name); return this; } @Override public IorderBulider addCoke(String name) { order.setCoke(name); return this; } @Override public IorderBulider addChicken(String name) { order.setChicken(name); return this; } @Override public IorderBulider addFruitjuice(String name) { order.setFruitjuice(name); return this; } @Override public Order buildOrder(){ return order; } }
测试:
public class Test { public static void main(String[] args) { IorderBulider iorderBulider = new OrderBuilder(); iorderBulider.addChicken("韩式炸鸡") .addCoke("百事可乐") .addHamburger("德式汉堡") .addFruitjuice("汇源果汁"); Order order = iorderBulider.buildOrder(); System.out.println(order); } }