原文 https://github.com/kamranahmedse/design-patterns-for-humans
作者用简练的语句概括几个设计模式的场景和用法,比看长篇大论心情舒畅多了,简要翻译一下加深记忆 #介绍 设计模式是对某种特定问题的解决之道 #注意 设计模式不是银弹
#设计模式的类型
- 创造型
- 结构型
- 行为型
#创造性设计模式 创造性设计模式专注于如何表达一个object或一组相关的object,通过从某种程度上控制这些object的创造
- 简单工厂模式
- 工厂模式
- 抽象工厂模式
- 建造者模式
- 原型模式
- 单例模式
##简单工厂 为你生成一个实例,掩盖所有生成的细节
###代码实例:
interface Door {
public function getWidth() : float;
public function getHeight() : float;
}
class WoodenDoor implements Door {
protected $width;
protected $height;
public function __construct(float $width, float $height) {
$this->width = $width;
$this->height = $height;
}
public function getWidth() : float {
return $this->width;
}
public function getHeight() : float {
return $this->height;
}
}
使用工厂建门
class DoorFactory {
public static function makeDoor($width, $height) : Door {
return new WoodenDoor($width, $height);
}
}
使用
$door = DoorFactory::makeDoor(100, 200);
echo 'Width: ' . $door->getWidth();
echo 'Height: ' . $door->getHeight();
###什么时候使用 当生成一个实例需要一定的逻辑,那把他们放在一个专用的工厂中会比散落在各处写相同的代码好
##工厂模式
让子类定义实例的逻辑,实现抽象父类的方法
###代码实例:
interface Interviewer {
public function askQuestions();
}
class Developer implements Interviewer {
public function askQuestions() {
echo 'Asking about design patterns!';
}
}
class CommunityExecutive implements Interviewer {
public function askQuestions() {
echo 'Asking about community building';
}
}
使用人事经理为不同的人决定是谁来面试
abstract class HiringManager {
// Factory method
abstract public function makeInterviewer() : Interviewer;
public function takeInterview() {
$interviewer = $this->makeInterviewer();
$interviewer->askQuestions();
}
}
创建各子类继承父类
class DevelopmentManager extends HiringManager {
public function makeInterviewer() : Interviewer {
return new Developer();
}
}
class MarketingManager extends HiringManager {
public function makeInterviewer() : Interviewer {
return new CommunityExecutive();
}
}
使用
$devManager = new DevelopmentManager();
$devManager->takeInterview(); // Output: Asking about design patterns
$marketingManager = new MarketingManager();
$marketingManager->takeInterview(); // Output: Asking about community building.
感觉使用接口也能达到同样的效果,不知为什么要绕道使用继承抽象父类的方式 ###什么时候使用
有共同的方法,但具体需在运行时决定使用哪个子类的逻辑