设计模式 四

原文 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";

转载于:https://my.oschina.net/u/3211934/blog/858099

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值