File tree 6 files changed +99
-1
lines changed
6 files changed +99
-1
lines changed Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace Creational \Prototype ;
4
+
5
+ abstract class BookPrototype
6
+ {
7
+ /**
8
+ * 标题
9
+ *
10
+ * @var string
11
+ */
12
+ protected $ title ;
13
+
14
+ /**
15
+ * 类型
16
+ *
17
+ * @var string
18
+ */
19
+ protected $ category ;
20
+
21
+ abstract public function __clone ();
22
+
23
+ public function getTitle (): string
24
+ {
25
+ return $ this ->title ;
26
+ }
27
+
28
+ public function setTitle (string $ title )
29
+ {
30
+ $ this ->title = $ title ;
31
+ }
32
+ }
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace Creational \Prototype ;
4
+
5
+ class ChineseBookPrototype extends BookPrototype
6
+ {
7
+ protected $ category = 'Chinese ' ;
8
+
9
+ public function __clone ()
10
+ {
11
+
12
+ }
13
+ }
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace Creational \Prototype ;
4
+
5
+ class EnglistBookPrototype extends BookPrototype
6
+ {
7
+ protected $ category = 'English ' ;
8
+
9
+ public function __clone ()
10
+ {
11
+
12
+ }
13
+ }
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace Creational \Prototype \Tests ;
4
+
5
+ use Creational \Prototype \ChineseBookPrototype ;
6
+ use Creational \Prototype \EnglistBookPrototype ;
7
+ use PHPUnit \Framework \TestCase ;
8
+
9
+ class PrototypeTest extends TestCase
10
+ {
11
+ public function testCanGetBook ()
12
+ {
13
+ $ chineseBook = new ChineseBookPrototype ();
14
+ $ englishBook = new EnglistBookPrototype ();
15
+
16
+ for ($ i = 0 ; $ i < 5 ; $ i ++) {
17
+ $ book = clone $ chineseBook ;
18
+ $ book ->setTitle ('中文书 No ' . $ i );
19
+ $ this ->assertInstanceOf (ChineseBookPrototype::class, $ book );
20
+ }
21
+
22
+ for ($ i = 0 ; $ i < 5 ; $ i ++) {
23
+ $ book = clone $ englishBook ;
24
+ $ book ->setTitle ('Englist Book No ' . $ i );
25
+ $ this ->assertInstanceOf (EnglistBookPrototype::class, $ book );
26
+ }
27
+ }
28
+
29
+ }
Original file line number Diff line number Diff line change 69
69
* 示例
70
70
71
71
> 场景:数据库连接。
72
+
73
+ ## 原型模式
74
+
75
+ * 简介
76
+
77
+ 为了避免以标准方式(构造函数)创建对象,而创建一个原型并将其克隆。
78
+ 当直接创建对象的代价比较大时,则采用这种模式。
79
+
80
+ * 示例
81
+
82
+ > 场景:创建不同类型的书。
Original file line number Diff line number Diff line change 13
13
- [x] 建造者模式
14
14
- [X] 对象池模式
15
15
- [x] 单例模式
16
- - [ ] 原型模式
16
+ - [x ] 原型模式
17
17
18
18
## 结构型
19
19
You can’t perform that action at this time.
0 commit comments