原文 https://github.com/kamranahmedse/design-patterns-for-humans
作者用简练的语句概括几个设计模式的场景和用法,比看长篇大论心情舒畅多了,简要翻译一下加深记忆 #介绍 设计模式是对某种特定问题的解决之道 #注意 设计模式不是银弹
#设计模式的类型
- 创造型
- 结构型
- 行为型
#结构性设计模式 结构性设计模式专注于如何表达事物与事物之间的关系,建立代码的组织结构
- 适配器模式
- 桥接模式
- 组合模式
- 装饰器模式
- 外观模式
- 享元模式
- 代理模式
##适配器模式
类似于两个不同国家人之间的翻译员。
能够在不改变已有class的代码接口的情况下,与其他接口合作。
###代码实例 一个猎人打猎狮子
interface Lion
{
public function roar();
}
class AfricanLion implements Lion
{
public function roar()
{
}
}
class AsianLion implements Lion
{
public function roar()
{
}
}
猎人能打猎各种狮子
class Hunter
{
public function hunt(Lion $lion)
{
}
}
之后猎人希望也能打猎野狗
// This needs to be added to the game
class WildDog
{
public function bark()
{
}
}
// Adapter around wild dog to make it compatible with our game
class WildDogAdapter implements Lion
{
protected $dog;
public function __construct(WildDog $dog)
{
$this->dog = $dog;
}
public function roar()
{
$this->dog->bark();
}
}
使用
$wildDog = new WildDog();
$wildDogAdapter = new WildDogAdapter($wildDog);
$hunter = new Hunter();
$hunter->hunt($wildDogAdapter);
##桥接模式 当你有个一网站,并且你提供各种主题选择,你是要给每一个页面都制作不同主题的副本,还是将不同的主题直接应用于同一个页面?
桥接模式提供后者的实现
桥接模式偏爱组合而非继承,将代码的一个层级抽出来交由另一个object实现,实现去偶。
###代码实例
我们的网站页面实现
interface WebPage
{
public function __construct(Theme $theme);
public function getContent();
}
class About implements WebPage
{
protected $theme;
public function __construct(Theme $theme)
{
$this->theme = $theme;
}
public function getContent()
{
return "About page in " . $this->theme->getColor();
}
}
class Careers implements WebPage
{
protected $theme;
public function __construct(Theme $theme)
{
$this->theme = $theme;
}
public function getContent()
{
return "Careers page in " . $this->theme->getColor();
}
}
被抽出的主题
interface Theme
{
public function getColor();
}
class DarkTheme implements Theme
{
public function getColor()
{
return 'Dark Black';
}
}
class LightTheme implements Theme
{
public function getColor()
{
return 'Off white';
}
}
class AquaTheme implements Theme
{
public function getColor()
{
return 'Light blue';
}
}
使用
$darkTheme = new DarkTheme();
$about = new About($darkTheme);
$careers = new Careers($darkTheme);
echo $about->getContent(); // "About page in Dark Black";
echo $careers->getContent(); // "Careers page in Dark Black";