《大话设计模式》装饰模式-穿什么场景-PHP版代码

Standard

装饰模式
穿什么场景

<?php
/**
 * 装饰模式 穿什么场景
 * @author 叶茂盛 anson.ye#gmail.com  http://yemaosheng.com
 */
interface Component{
        public function Show();
}
 
class Person implements Component{
        protected $_name;
 
        public function __construct($name){
                $this->_name = $name;
        }
        public function Show(){
                echo "装扮的".$this->_name;
        }
}
 
 
abstract class Finery implements Component{
        protected $_component;
        public function Decorate(Component $component){
                $this->_component = $component;
        }
        public function Show(){
                $this->_component->Show();
        }
}
class Sneakers extends Finery{
        public function Show(){
                echo "旅游鞋 ";
                parent::Show();
        }
}
class TShirts extends Finery{
        public function Show(){
                echo "T恤 ";
                parent::Show();
        }
}
class BigTrouser extends Finery{
        public function Show(){
                echo "垮裤 ";
                parent::Show();
        }
}
class Tie extends Finery{
        public function Show(){
                echo "领带 ";
                parent::Show();
        }
}
class Suit extends Finery{
        public function Show(){
                echo "西装 ";
                parent::Show();
        }
}
class LeatherShoes extends Finery{
        public function Show(){
                echo "皮鞋 ";
                parent::Show();
        }
}
class Main{
        public static function run(){
                $xc = new Person("小菜");
 
                $sk = new Sneakers();
                $ts = new TShirts();
                $bt = new BigTrouser();
 
                echo "装扮1:\n";
                $sk->Decorate($xc);
                $ts->Decorate($sk);
                $bt->Decorate($ts);
                $bt->Show();
 
                $dn = new Person("大鸟");
 
                $ti = new Tie();
                $si = new Suit();
                $ls = new LeatherShoes();
 
                echo "\n装扮2:\n";
                $ti->Decorate($dn);
                $si->Decorate($ti);
                $ls->Decorate($si);
                $ls->Show();
 
        }
}
Main::run();
?>
//php Decorator.php 
//装扮1:
//垮裤 T恤 旅游鞋 装扮的小菜
//装扮2:
//皮鞋 西装 领带 装扮的大鸟

转载请注明出处 http://yemaosheng.com

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.