建造者模式:
将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示的设计模式;
目的:
消除其他对象复杂的创建过程
结构图:
优点:
建造者模式可以很好的将一个对象的实现与相关的“业务”逻辑分离开来,从而可以在不改变事件逻辑的前提下,使增加(或改变)实现变得非常容易。
缺点:
建造者接口的修改会导致所有执行类的修改。
以下情况应当使用建造者模式:
1、 需要生成的产品对象有复杂的内部结构。
2、 需要生成的产品对象的属性相互依赖,建造者模式可以强迫生成顺序。
3、 在对象创建过程中会使用到系统中的一些其它对象,这些对象在产品对象的创建过 程中不易得到。
使用建造者模式主要有以下效果:
1、 建造者模式的使用使得产品的内部表象可以独立的变化。使用建造者模式可以使客 户端不必知道产品内部组成的细节。
2、 每一个Builder都相对独立,而与其它的Builder无关。
3、 模式所建造的最终产品更易于控制。
代码实现:
1 /1** 2 3 * 建造者模式 4 5 * 将一个复杂对象的构造与它的表示分离,是同样的构建过程可以创建不同的表示; 6 7 * 目的是为了消除其他对象复杂的创建过程 8 9 */ 10 11 12 13 /1** 14 15 * 产品,包含产品类型、价钱、颜色属性 16 17 */ 18 19 class Product 20 21 { 22 23 public $_type = null; 24 25 public $_price = null; 26 27 public $_color = null; 28 29 30 31 public function setType($type) 32 33 { 34 35 echo 'set the type of the product,'; 36 37 $this->_type = $type; 38 39 } 40 41 42 43 public function setPrice($price) 44 45 { 46 47 echo 'set the price of the product,'; 48 49 $this->_price = $price; 50 51 } 52 53 54 55 public function setColor($color) 56 57 { 58 59 echo 'set the color of the product,'; 60 61 $this->_color = $color; 62 63 } 64 65 } 66 67 68 69 $config = array( 70 71 'type' => 'shirt', 72 73 'price' => 100, 74 75 'color' => 'red', 76 77 ); 78 79 80 81 //不使用builder模式 82 83 $product = new Product(); 84 85 $product->setType($config['type']); 86 87 $product->setPrice($config['price']); 88 89 $product->setColor($config['color']); 90 91 92 93 //使用builder模式 94 95 /1** 96 97 * builder类 98 99 */ 100 101 class ProductBuilder 102 103 { 104 105 public $_config = null; 106 107 public $_object = null; 108 109 110 111 public function ProductBuilder($config) 112 113 { 114 115 $this->_object = new Product(); 116 117 $this->_config = $config; 118 119 } 120 121 122 123 public function build() 124 125 { 126 127 echo '<br />Using builder pattern:<br />'; 128 129 $this->_object->setType($this->_config['type']); 130 131 $this->_object->setPrice($this->_config['price']); 132 133 $this->_object->setColor($this->_config['color']); 134 135 } 136 137 138 139 public function getProduct() 140 141 { 142 143 return $this->_object; 144 145 } 146 147 } 148 149 150 151 $objBuilder = new ProductBuilder($config); 152 153 $objBuilder->build(); 154 155 $objProduct = $objBuilder->getProduct(); 156 157 echo '<br />'; 158 159 var_dump($objProduct);