原文 https://github.com/kamranahmedse/design-patterns-for-humans
作者用简练的语句概括几个设计模式的场景和用法,比看长篇大论心情舒畅多了,简要翻译一下加深记忆 #介绍 设计模式是对某种特定问题的解决之道 #注意 设计模式不是银弹
#设计模式的类型
- 创造型
- 结构型
- 行为型
#创造性设计模式 创造性设计模式专注于如何表达一个object或一组相关的object,通过从某种程度上控制这些object的创造
- 简单工厂模式
- 工厂模式
- 抽象工厂模式
- 建造者模式
- 原型模式
- 单例模式
##原型模式
通过拷贝一个存在的实例来创建新实例
###代码实例
在php中,可以直接使用clone
class Sheep
{
protected $name;
protected $category;
public function __construct(string $name, string $category = 'Mountain Sheep')
{
$this->name = $name;
$this->category = $category;
}
public function setName(string $name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setCategory(string $category)
{
$this->category = $category;
}
public function getCategory()
{
return $this->category;
}
}
使用clone
$original = new Sheep('Jolly');
echo $original->getName(); // Jolly
echo $original->getCategory(); // Mountain Sheep
// Clone and modify what is required
$cloned = clone $original;
$cloned->setName('Dolly');
echo $cloned->getName(); // Dolly
echo $cloned->getCategory(); // Mountain sheep
###什么时候使用
想要创建一个与已有实例非常相似的实例时,或者创建过程的成本大于clone时。
##单例模式
单例模式保证一个class只产生一个实例
单例模式的过度使用是需要被避免的,因为它创建了一个全局状态,使得代码过于耦合
###代码实例
让构造方法私有化,不开放继承,再创建一个私有的静态变量持有实例
final class President
{
private static $instance;
private function __construct()
{
// Hide the constructor
}
public static function getInstance(): President
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __clone()
{
// Disable cloning
}
private function __wakeup()
{
// Disable unserialize
}
}
使用
$president1 = President::getInstance();
$president2 = President::getInstance();
var_dump($president1 === $president2); // true