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

Posted foolishnoob

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 DesignPatternBlueMountainCoffee();//生成一杯蓝山咖啡
$beverage = new DesignPatternMilkDecorator($coffee);//给蓝山咖啡加一份牛奶
$beverage = new DesignPatternMilkDecorator($beverage);//给蓝山咖啡再加一份牛奶
$beverage = new DesignPatternSugarDecorator($beverage);//给蓝山咖啡加一份糖
$beverage = new DesignPatternSugarDecorator($beverage);//给蓝山咖啡再加一份糖
$beverage = new DesignPatternSugarDecorator($beverage);//给蓝山咖啡再加一份糖
var_dump($beverage->getCost());

程序运行结果:

float(26.6)

以上是关于php设计模式之:装饰者模式的主要内容,如果未能解决你的问题,请参考以下文章

Java设计模式之装饰者模式

设计模式 之 装饰者模式

设计模式之装饰者模式

设计模式之装饰者模式

Java设计模式之装饰者模式

JAVA设计模式之装饰者模式