Design Pattern -- Builder模式

2018-04-02  本文已影响12人  androidjp

引言:Builder模式有“链式调用”、封装对象构建过程 的 作用。 这里直接用一个例子来说明吧。


Design Pattern -- Builder pattern

一、场景


如果你开了一家店,专门负责电脑组装的,每一个客户想要的电脑零件牌子和CPU等不一样,你最终可以提供的成本电脑有:MacBookPro 等等。

二、设计 与 代码


public class Director {
  public static final String MAC_BOOK_PRO_13_i5 = "MAC_BOOK_PRO_13_i5";
  public static final String MAC_BOOK_PRO_15_i7 = "MAC_BOOK_PRO_15_i7";

  public Computer construct(String brand) {
    ComputerBuilder computerBuilder = null;

    if (MAC_BOOK_PRO_13_i5.equals(brand)) {
      computerBuilder = new MacBookPro13i5Builder();
    } else if (MAC_BOOK_PRO_15_i7.equals(brand)) {
      computerBuilder = new MacBookPro15i7Builder();
    }

    return computerBuilder
        .buildCpu()
        .buildScreen()
        .build();
  }
}
public abstract class ComputerBuilder {

    //设置屏幕等
    public abstract ComputerBuilder buildScreen();
    
    //设置cpu型号等
    public abstract ComputerBuilder buildCpu();

    ///重要!!!最终返回一个目的类对象实例
    public abstract Computer build();
}
public class Computer {
    private String brand;
    private String screen;
    private String cpu;
    private String os;
//............
}
public class MacBookPro13i5Builder extends ComputerBuilder {

  private Computer computer = new Computer();
  {
    computer.setBrand("MacBookPro");
    computer.setOs("MacOS");
  }

  @Override
  public ComputerBuilder buildScreen() {
    this.computer.setScreen("Retina15寸");
    return this;
  }

  @Override
  public ComputerBuilder buildCpu() {
    this.computer.setCpu("i7");
    return this;
  }

  @Override
  public Computer build() {
    return this.computer;
  }
}
public class MacBookPro15i7Builder extends ComputerBuilder {

  private Computer computer = new Computer();
  {
    computer.setBrand("MacBookPro");
    computer.setOs("MacOS");
  }
  @Override
  public ComputerBuilder buildScreen() {
    this.computer.setScreen("Retina13寸");
    return this;
  }

  @Override
  public ComputerBuilder buildCpu() {
    this.computer.setCpu("i5");
    return this;
  }

  @Override
  public Computer build() {
    return this.computer;
  }
}
运行效果
上一篇 下一篇

猜你喜欢

热点阅读