码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2018-07-04 01:14:42      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:装饰者模式   结果   end   pat   kde   装饰者   protected   ring   程序   

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)

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

标签:装饰者模式   结果   end   pat   kde   装饰者   protected   ring   程序   

原文地址:https://www.cnblogs.com/foolishnoob/p/9261219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!