设计模式之建造者模式--PHP

建造者模式:将一个负责对象的构建与它的表示分离,使得同样的构建过程有不同的表示。建造者模式是一步一步创建负责的对象,它允许开发者只通过指定对象的类型和内容就可以创建它们。开发者不需要知道具体的构造细节。

UML图:

构造者模式的demo

 1 <?php
 2 /**
 3  * @desc 建造者模式
 4  * Created by PhpStorm.
 5  * User: zzq
 6  * Date: 2019-02-14
 7  * Time: 16:22
 8  */
 9 
10 //定义一个对象,这里只有对象属性
11 class People{
12     public $head;
13     public $body;
14     public $foot;
15     public function __construct(){
16     }
17 }
18 //建造者的抽象类,所有建造者都到实现的方法
19 abstract class PeopleBuilder{
20     abstract function headBuilder();
21     abstract function bodyBuilder();
22     abstract function footBuilder();
23     abstract function returnResult();
24 }
25 //真正的建造者
26 class childernBuilder extends PeopleBuilder{
27     public $people;
28     public function __construct(){
29         $this->people = new People();
30     }
31 
32     function headBuilder(){
33         $this->people->head = 'this is child\'s head';
34         echo PHP_EOL;
35     }
36 
37     function bodyBuilder(){
38         $this->people->body = 'this is child\'s body';
39         echo PHP_EOL;
40     }
41 
42     function footBuilder(){
43         $this->people->foot = 'this is child\'s foot';
44         echo PHP_EOL;
45     }
46 
47     function returnResult(){
48         return $this->people;
49     }
50 }
51 //指挥者,用来指挥建造者的行为动作
52 class Director{
53     function __construct(PeopleBuilder $peopleBuilder){
54         $peopleBuilder->headBuilder();
55         $peopleBuilder->bodyBuilder();
56         $peopleBuilder->footBuilder();
57     }
58 }
59 //测试方法
60 $builder = new childernBuilder();
61 $director = new Director($builder);
62 $people = $builder->returnResult();
63 print_r($people);

demo执行结果

People Object
(
    [head] => this is child's head
    [body] => this is child's body
    [foot] => this is child's foot
)

建造者模式的优点:

  建造者模式可以很好地将一个对象的实现和相关的业务逻辑分离开来,从而在不改变事件逻辑的前提下,使增加或者改变实现变得容易的很多。

建造模式的缺点:

  建造者接口的修改会导致所有执行类也要变动。

 

posted @ 2019-02-14 17:19  青竹zzq  阅读(249)  评论(0编辑  收藏  举报