设计模式一:装饰器模式

装饰器模式

  在不改变对象的基础上,动态对的将新的功能职责赋加给该对象。

<?php
/**
 * 抽象组件类
 */
interface MobileCase{
    public function boot();
}
/**
 * 抽象组件实现类
 */
class Mobile implements MobileCase{
 
    public function boot()
    {
        echo '透明手机壳:售价20元'.PHP_EOL;
    }
}

/**
 * 装饰器 抽象组件类
 */
abstract class MobileDecorator implements MobileCase{
    protected $mobileCase;

    public function __construct(MobileCase $mobileCase){
        $this->mobileCase = $mobileCase;
    }

    public function boot(){
        $this->mobileCase->boot();
    }
}

/**
 * 装饰器实现类
 */
class RedMobile extends MobileDecorator{
    private $name = '红色手机壳';

    private function add(){
        echo $this->name .':加10元'.PHP_EOL;
    }

    public function boot(){
        $this->mobileCase->boot();
        $this->add();
    }
}

/**
 * 装饰器实现类
 */
class YellowMobile extends MobileDecorator{
    private $name = '黄色手机壳';

    private function add(){
        echo $this->name .':加5元'.PHP_EOL;
    }

    public function boot(){
        $this->mobileCase->boot();
        $this->add();
    }
}

/**
 * 客户端
 */
class Client{
    public function run(){
        $mobile = new Mobile();
        $redMobile = new RedMobile($mobile);
        $redMobile->boot();
    }
}

$client = new Client();
$client->run();

 

posted @ 2021-08-23 14:47  wish_yang  阅读(40)  评论(0编辑  收藏  举报