[php]php设计模式 Builder(建造者模式)
1 <?php
2 /**
3 * 建造者模式
4 *
5 * 将一个复杂对象的构建与它的表示分离,使用同样的构建过程可以创建不同的表示
6 */
7 class Product
8 {
9 public$_type=null;
10 public$_size=null;
11 public$_color=null;
12
13 publicfunctionsetType($type)
14 {
15 echo"set product type<br/>";
16 $this->_type =$type;
17 }
18
19 publicfunction setSize($size)
20 {
21 echo"set product size<br/>";
22 $this->_size =$size;
23 }
24
25 publicfunction setColor($color)
26 {
27 echo"set product color<br/>";
28 $this->_color =$color;
29 }
30 }
31
32 $config=array(
33 "type"=>"shirt",
34 "size"=>"xl",
35 "color"=>"red",
36 );
37
38 // 没有使用bulider以前的处理
39 $oProduct=new Product();
40 $oProduct->setType($config['type']);
41 $oProduct->setSize($config['size']);
42 $oProduct->setColor($config['color']);
43
44
45 // 创建一个builder类
46 class ProductBuilder
47 {
48 var$_config=null;
49 var$_object=null;
50
51 publicfunction ProductBuilder($config)
52 {
53 $this->_object =new Product();
54 $this->_config =$config;
55 }
56
57 publicfunction build()
58 {
59 echo"--- in builder---<br/>";
60 $this->_object->setType($this->_config['type']);
61 $this->_object->setSize($this->_config['size']);
62 $this->_object->setColor($this->_config['color']);
63 }
64
65 publicfunction getProduct()
66 {
67 return$this->_object;
68 }
69 }
70
71 $objBuilder=new ProductBuilder($config);
72 $objBuilder->build();
73 $objProduct=$objBuilder->getProduct();
2 /**
3 * 建造者模式
4 *
5 * 将一个复杂对象的构建与它的表示分离,使用同样的构建过程可以创建不同的表示
6 */
7 class Product
8 {
9 public$_type=null;
10 public$_size=null;
11 public$_color=null;
12
13 publicfunctionsetType($type)
14 {
15 echo"set product type<br/>";
16 $this->_type =$type;
17 }
18
19 publicfunction setSize($size)
20 {
21 echo"set product size<br/>";
22 $this->_size =$size;
23 }
24
25 publicfunction setColor($color)
26 {
27 echo"set product color<br/>";
28 $this->_color =$color;
29 }
30 }
31
32 $config=array(
33 "type"=>"shirt",
34 "size"=>"xl",
35 "color"=>"red",
36 );
37
38 // 没有使用bulider以前的处理
39 $oProduct=new Product();
40 $oProduct->setType($config['type']);
41 $oProduct->setSize($config['size']);
42 $oProduct->setColor($config['color']);
43
44
45 // 创建一个builder类
46 class ProductBuilder
47 {
48 var$_config=null;
49 var$_object=null;
50
51 publicfunction ProductBuilder($config)
52 {
53 $this->_object =new Product();
54 $this->_config =$config;
55 }
56
57 publicfunction build()
58 {
59 echo"--- in builder---<br/>";
60 $this->_object->setType($this->_config['type']);
61 $this->_object->setSize($this->_config['size']);
62 $this->_object->setColor($this->_config['color']);
63 }
64
65 publicfunction getProduct()
66 {
67 return$this->_object;
68 }
69 }
70
71 $objBuilder=new ProductBuilder($config);
72 $objBuilder->build();
73 $objProduct=$objBuilder->getProduct();
think in coding