胡桃仁

虚度光阴27 载

建造者模式(Builder)—-对象创建型模式

1、介绍

将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

  • 适用于需要的对象在初始化时需要传入太多的参数。

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php

class Message
{
public $title;
public $content;

public function __toString(): string
{
return "Message{" .
"标题='" . $this->title . "'" .
", 内容='" . $this->content . "'" .
"}</br>\n";
}
}

interface MessageBuilder
{
public function getTile();

public function getContent();

public function getMessage(): Message;
}

// 具体构造者---微信消息构造者
class WechatMsgBuilder implements MessageBuilder
{

private $message;

public function __construct()
{
$this->message = new Message();
}

public function getTile()
{
$this->message->title = "微信消息--title";
}

public function getContent()
{
$this->message->content = "微信消息--content";
}

public function getMessage(): Message
{
return $this->message;
}
}

// 具体构造者---短信构造者
class ShortMsgBuilder implements MessageBuilder
{
private $message;
public function __construct()
{
$this->message = new Message();
}

public function getTile()
{
$this->message->title = "短信消息--title";
}

public function getContent()
{
$this->message->content = "短信消息--content";
}

public function getMessage(): Message
{
return $this->message;
}
}

// director
class MessageDirector
{
public function builder(MessageBuilder $messageBuilder): Message
{
$messageBuilder->getTile();
$messageBuilder->getContent();
return $messageBuilder->getMessage();
}
}


/*************************** 以下测试 ********************************/

$houseDirector = new MessageDirector();

$wechatMsgBuilder = new WechatMsgBuilder();
echo $houseDirector->builder($wechatMsgBuilder);

$shortMsgBuilder = new ShortMsgBuilder();
echo $houseDirector->builder($shortMsgBuilder);

/** 结果
Message{标题='微信消息--title', 内容='微信消息--content'}
Message{标题='短信消息--title', 内容='短信消息--content'}
**/

总结TODO

评论