设计模式

设计模式 装饰模式

2020-06-10  本文已影响0人  Yohann丶blog
WechatIMG31.jpeg

介绍

装饰模式,可称为装饰器模式或修饰模式,是面向对象编程领域中,一种动态地往一个类中添加新的行为的设计模式。在原有的基础上进行功能增强。就功能而言,装饰模式相比生成子类更为灵活,这样可以给某个对象而不是整个类添加一些功能。特点是用来增强原有对象功能,依附于原有对象。应用在用于需要对原有对象增加功能而不是完全覆盖的场景。

角色

角色 说明
Component 抽象构件
ConcreteComponent 具体构件
Decorator 抽象装饰类
ConcreteDecorator 具体装饰类

角色示例

类名 担任角色 说明
SocialSoftware Component 社交软件
Wechat ConcreteComponent 微信
SetWechat Decorator 微信设置
Voice ConcreteDecorator 语音
Video ConcreteDecorator 视频

UML类图

装饰模式.jpg

代码

<?php
abstract class SocialSoftware
{
    abstract function chat();
}

class Wechat extends SocialSoftware 
{
    public function chat() {
        return '聊天';
    }
}

class SetWechat extends SocialSoftware {
    protected $wechat;

    protected $special;

    function __construct($wechat) {
        $this->wechat = $wechat;
    }

    public function chat() {
        return $this->special.$this->wechat->chat();
    }
}

class Voice extends SetWechat {
    protected $special = '语音';
}

class Video extends SetWechat {
    protected $special = '视频';
}

$wechat = new Wechat();
echo $wechat->chat().PHP_EOL;

$wechat = new Voice($wechat);
echo $wechat->chat().PHP_EOL;

$wechat = new Video($wechat);
echo $wechat->chat().PHP_EOL;

创建 Wechat.php,内容如上。

执行

$ php Wechat.php
聊天
语音聊天
视频语音聊天
上一篇 下一篇

猜你喜欢

热点阅读