建造者模式

来源:互联网 发布:淘宝拍图动作 编辑:程序博客网 时间:2024/06/07 22:55

建造者模式是为了解决工厂模式和抽象工厂模式当对象包含大量的属性问题。

当工厂模式和抽象工厂模式的对象存在大量属性的时候存在三个主要的问题。

  • 从客户端程序传递给工厂类的参数太多,很容易出错,因为大部分时间,参数的类型相同,客户端它很难维护参数的顺序。

  • 某些参数可能是可选的,但在工厂模式,我们被迫把所有的参数和将null做为需要发送的可选 
    参数。

  • 不易维护,构造方法的灵活性较低。

    我们可以通过一种必须传递参数的构造方法,然后通过不同的setter()方法来设置可选参数,从而解决大量参数的问题。 
    但这个问题是,对象的状态会不一致,除非所有的属性被显示设置。

    Builder模式提供了一个方法来建立对象解决了大量的可选参数和状态不一致的问题,一步一步,并提供实际上将返回的最终对象的方法

建造者模式的实现

  1. 首先需要创建一个静态嵌套类,然后从外部类拷贝所有的参数到builder类。我们应该遵循这样的命名惯例, 
    如果类的名称是Computer,那么builder类应该命名为ComputerBuilder

  2. 建造者类(builder class)应该有一个带有必须属性参数的公共构造方法.

  3. builder类应该有方法来设置可选参数并且在设置可选属性后应该返回同样的builder对象.

  4. 最后一步在builder类提供一个build()方法来返回客户端需要的对象. 
    因此,我们需要一个将builder类作为参数的私有的构造方法

    以下就是示例代码.

    public class Computer { 
    private String HDD;

    private String ARM;private boolean isGraphicCardEnable;private boolean isBluetoothEnable;private Computer(ComputerBuilder builder){    this.ARM = builder.ARM;    this.HDD = builder.HDD;    this.isGraphicCardEnable = builder.isGraphicCardEnable;    this.isBluetoothEnable = builder.isBluetoothEnable;}public String getHDD() {    return HDD;}public String getARM() {    return ARM;}public boolean isGraphicCardEnable() {    return isGraphicCardEnable;}public boolean isBluetoothEnable() {    return isBluetoothEnable;}public static class ComputerBuilder{    private String HDD;    private String ARM;    private boolean isGraphicCardEnable;    private boolean isBluetoothEnable;    public ComputerBuilder(String hdd,String arm){        this.HDD = hdd;        this.ARM = arm;    }    public ComputerBuilder setIsGraphicCardEnable(boolean isGraphicCardEnable){        this.isGraphicCardEnable = isGraphicCardEnable;        return this;    }    public ComputerBuilder setIsBluetoothEnable(boolean isBluetoothEnable){        this.isBluetoothEnable = isBluetoothEnable;        return this;    }    public Computer builder(){        return new Computer(this);    }}

    }

    测试类:

    public class TestBuilderPattern {

    public static void main(String args[]){    Computer computer = new Computer.ComputerBuilder("500g","2g")            .setIsGraphicCardEnable(true).setIsGraphicCardEnable(true)            .builder();    System.out.println("ARM:"+computer.getARM()+" HDD:" + computer.getHDD());}

    }

jdk中的建造者模式例子


  • java.lang.StringBuilder#append() (unsynchronized)
  • java.lang.StringBuffer#append() (synchronized)
0 0