PHP设计模式 - 装饰模式
in PHP with 0 comment

PHP设计模式 - 装饰模式

in PHP with 0 comment

装饰模式类图

装饰模式:动态地给对象添加一些额外的职责。就功能来说装饰模式相比子类更加灵活

<?php
/**
 * TODO Auto-generated comment.
 */
abstract class Bird {

    /**
     * TODO Auto-generated comment.
     */
    public function fly() {
        return 0;
    }
}
<?php
/**
 * TODO Auto-generated comment.
 */
class Sparrow extends Bird {
    const DISTANCE = 100;
    /**
     * TODO Auto-generated comment.
     */
    public function fly() {
        return self::DISTANCE;
    }
}
<?php
/**
 * TODO Auto-generated comment.
 */
abstract class Decorator extends Bird {
    /**
     * TODO Auto-generated comment.
     */
    protected $bird;
    public function __construct($bird){
        $this->bird = $bird;
    }
    /**
     * TODO Auto-generated comment.
     */
    public function fly() {
        return 0;
    }
}
<?php
/**
 * TODO Auto-generated comment.
 */
class SparrowDecorator extends Decorator {
    const DISTANCE = 50;
    /**
     * TODO Auto-generated comment.
     */
    public function __construct($bird){
        parent::__construct($bird);
    }
    public function fly() {
        return $this->bird->fly()+$this->elefly();
    }

    /**
     * TODO Auto-generated comment.
     */
    public function elefly() {
        return self::DISTANCE;
    }
}
<?php
/**
 * @Author: Cizel
 * @Date:   2016-04-09 11:15:11
 * @Last Modified by:   Cizel
 * @Last Modified time: 2016-04-09 11:36:03
 */
function __autoload($classname) {
    require_once($classname.".php");
}

$sparrow = new Sparrow();
$sparrowDecorator = new SparrowDecorator($sparrow);
$sparrowDecorator1 = new SparrowDecorator($sparrowDecorator);
echo "this bird can fly ".$sparrowDecorator->fly()." m <br />";
echo "this bird can fly ".$sparrowDecorator1->fly()." m";

我的理解:装饰模式就是为一个抽象类添加一个装饰类,装饰类的作用就是,加强继承抽象类的具体类中的某一个方法功能。
满足面向对象的设计原则:少用继承,多用组合

Responses