Skip to content

Commit 0b07c10

Browse files
committed
feat(prototype) : code & test & readme
1 parent b8c6e70 commit 0b07c10

File tree

6 files changed

+99
-1
lines changed

6 files changed

+99
-1
lines changed
+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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 numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
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 numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
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 numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

Creational/README.md

+11
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,14 @@
6969
* 示例
7070

7171
>场景:数据库连接。
72+
73+
## 原型模式
74+
75+
* 简介
76+
77+
为了避免以标准方式(构造函数)创建对象,而创建一个原型并将其克隆。
78+
当直接创建对象的代价比较大时,则采用这种模式。
79+
80+
* 示例
81+
82+
>场景:创建不同类型的书。

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
- [x] 建造者模式
1414
- [X] 对象池模式
1515
- [x] 单例模式
16-
- [ ] 原型模式
16+
- [x] 原型模式
1717

1818
## 结构型
1919

0 commit comments

Comments
 (0)