php设计模式之:装饰者模式

Beverage.php

<?php
namespace DesignPattern;

abstract class Beverage
{
    /**
     * @var string
     */
    protected $name = '';

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @param string $name
     * @return Beverage
     */
    public function setName(string $name): Beverage
    {
        $this->name = $name;
        return $this;
    }

    /**
     * @return float
     */
    public abstract function getCost(): float;

    /**
     * Beverage constructor.
     */
    public function __construct()
    {
    }
}

BlueMountainCoffee.php

<?php

namespace DesignPattern;
/**
 * 蓝山咖啡
 */
class BlueMountainCoffee extends Beverage
{

    /**
     * @return float
     */
    public function getCost(): float
    {
        return 18.0;
    }
}

CubitaCoffee.php

<?php

namespace DesignPattern;
/**
 * 琥爵咖啡
 */
class CubitaCoffee extends Beverage
{

    /**
     * @return float
     */
    public function getCost(): float
    {
        return 24.0;
    }
}

CoffeeDecorator.php

<?php

namespace DesignPattern;

abstract class CoffeeDecorator extends Beverage
{
    /**
     * @var CoffeeDecorator
     */
    protected $coffeeDecorator;

    /**
     * CoffeeDecorator constructor.
     * @param Beverage $coffeeDecorator
     */
    public function __construct(Beverage $coffeeDecorator)//特别需要注意这个地方,装饰者模式必须允许对装饰后的对象再次装饰
    {
        parent::__construct();
        $this->coffeeDecorator = $coffeeDecorator;
    }
}

MilkDecorator.php

<?php

namespace DesignPattern;

class MilkDecorator extends CoffeeDecorator
{
    /**
     * @return float
     */
    public function getCost(): float
    {
        return $this->coffeeDecorator->getCost() + 2.5;
    }
}

SugarDecorator.php

<?php

namespace DesignPattern;

class SugarDecorator extends CoffeeDecorator
{

    /**
     * @return float
     */
    public function getCost(): float
    {
        return $this->coffeeDecorator->getCost() + 1.2;
    }
}

最终调用:

$coffee = new \DesignPattern\BlueMountainCoffee();//生成一杯蓝山咖啡
$beverage = new \DesignPattern\MilkDecorator($coffee);//给蓝山咖啡加一份牛奶
$beverage = new \DesignPattern\MilkDecorator($beverage);//给蓝山咖啡再加一份牛奶
$beverage = new \DesignPattern\SugarDecorator($beverage);//给蓝山咖啡加一份糖
$beverage = new \DesignPattern\SugarDecorator($beverage);//给蓝山咖啡再加一份糖
$beverage = new \DesignPattern\SugarDecorator($beverage);//给蓝山咖啡再加一份糖
var_dump($beverage->getCost());

程序运行结果:

float(26.6)
posted @ 2018-07-03 23:37  一叶(foolishnoob)  阅读(229)  评论(0编辑  收藏  举报