Rumah  >  Artikel  >  pembangunan bahagian belakang  >  PHP设计模式之装饰器模式详解

PHP设计模式之装饰器模式详解

韦小宝
韦小宝asal
2017-11-15 09:51:241937semak imbas

装饰器模可以动态的添加修改类的功能,.个类提供了一项功能,如果要在修改并添加额外的功能,传统的编程是写一个子类去继承它,并重新实现类的方法,使用装饰器模式,仅需在运行时添加一个装饰器对象即可实现,可以实现最大的灵活性

2Q1NPR5TIHQ1ROZ~0LMK@FJ.png

<?php

/*
 * 装饰模式
 */

abstract class Beverage
{
    public $_name;

    abstract public function Cost();
}

// 被装饰者类
class Coffee extends Beverage
{
    public function construct()
    {
        $this->_name = &#39;Coffee&#39;;
    }

    public function Cost()
    {
        return 1.00;
    }
}

// 以下三个类是装饰者相关类
class CondimentDecorator extends Beverage //装饰类
{
    public function construct()
    {
        $this->_name = &#39;Condiment&#39;;
    }

    public function Cost()
    {
        return 0.1;
    }
}

class Milk extends CondimentDecorator //牛奶 配料 --装饰者
{
    public $_beverage;

    public function construct($beverage)
    {
        if ($beverage instanceof Beverage) {
            $this->_beverage = $beverage;
        } else
            exit(&#39;Failure&#39;);
    }

    public function Cost()
    {
        return $this->_beverage->Cost() + 0.2;
    }
}

class Sugar extends CondimentDecorator //糖 配料 --装饰者
{
    public $_beverage;

    public function construct($beverage)
    {
        $this->_name = &#39;Sugar&#39;;
        if ($beverage instanceof Beverage) {
            $this->_beverage = $beverage;
        } else {
            exit(&#39;Failure&#39;);
        }
    }

    public function Cost()
    {
        return $this->_beverage->Cost() + 0.2;
    }
}

// Test Case
//1.拿杯咖啡
$coffee = new Coffee();

//2.加点牛奶
$coffee = new Milk($coffee);

//3.加点糖
$coffee = new Sugar($coffee);

echo $coffee->Cost();
echo $coffee->_name;

装饰模式降低了系统的耦合度,可以动态增加或删除对象的职责,并使得需要装饰的具体构件类和具体装饰类可以独立变化,以便增加新的具体构件类和具体装饰类

相关推荐:

详解PHP装饰模式的示例代码

php装饰模式

易懂的PHP设计模式之单例模式

Atas ialah kandungan terperinci PHP设计模式之装饰器模式详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn