@Chiang
2019-12-30T17:03:09.000000Z
字数 2007
阅读 429
设计模式
饮品接口
<?php
/**
* Drinks.php
*
* @author Luffy (lufei@swoole.com)
* @date 2019/11/15
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\Decorator;
interface Drinks
{
public function name();
public function price();
}
茶类 实现饮品接口
<?php
/**
* Tea.php
*
* @author Luffy (lufei@swoole.com)
* @date 2019/11/15
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\Decorator;
class Tea implements Drinks
{
public function name()
{
return '茶';
}
public function price()
{
return 10;
}
}
装饰器抽象类 实现饮品接口 茶类注入
<?php
/**
* Decorator.php 装饰器
*
* @author Luffy (lufei@swoole.com)
* @date 2019/11/15
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\Decorator;
abstract class Decorator implements Drinks
{
/**
* @var Drinks
*/
protected $drinks;
/**
* Decorator constructor.
*
* @param Drinks $drinks
*/
public function __construct(Drinks $drinks)
{
$this->drinks = $drinks;
}
}
红茶 继承装饰器
<?php
/**
* BlackTea.php 红茶
*
* @author Luffy (lufei@swoole.com)
* @date 2019/11/15
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\Decorator;
class BlackTea extends Decorator
{
public function name()
{
return '柠檬红'.$this->drinks->name();
}
public function price()
{
return $this->drinks->price() + 5;
}
}
奶茶 继承装饰器
<?php
/**
* MilkTea.php 奶茶
*
* @author Luffy (lufei@swoole.com)
* @date 2019/11/15
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\Decorator;
class MilkTea extends Decorator
{
public function name()
{
return '珍珠奶'.$this->drinks->name();
}
public function price()
{
return $this->drinks->price() + 8;
}
}
客户端 对象注入
<?php
/**
* Client.php
*
* @author Luffy (lufei@swoole.com)
* @date 2019/11/15
* @copyright Swoole, Inc.
* @package sy-records/design-patterns
*/
namespace Luffy\DesignPatterns\Decorator;
require __DIR__ . '/../vendor/autoload.php';
class Client
{
public static function run()
{
$tea = new Tea();
echo $tea->name();
echo $tea->price()."元\n";
$blackTea = new BlackTea($tea);
echo $blackTea->name();
echo $blackTea->price()."元\n";
$milkTea = new MilkTea($tea);
echo $milkTea->name();
echo $milkTea->price()."元\n";
}
}
Client::run();