php八大设计模式之装饰器模式

  我们都知道,得到一匹布需要大概这么几步:
       1、染色
       2、印花
       3、裁剪
  这种形式在面向对象中怎么实现呢?

面向过程【继承模式】实现:

    继承模式得到需要的布料,一步一步的加工。 
    继承的层次越来越深,扩展性差。如果中间加道其他程序,就有些吃力了。
<?php
    header("content-type:text/html;charset=utf8");
    class BaseCloth{         //布料初始的样子
        protected $content;
        public function __construct($con){
            $this->content=$con;
        }
        public function cloth(){
            return $this->content;
        }
    }
    class DyeingCloth extends BaseCloth{   //染色
        public function dyeing(){
            return $this->content."  --->染上色";
        }
    }
    class StampCloth extends DyeingCloth{   //印花
        public function stamp(){
            return $this->content."  --->印上好看的花";
        }
    }
    class CutCloth extends StampCloth{      //裁剪
        public function cut(){
            return $this->content."  --->根据需求裁剪";
        }
    }



    //布料加工。
    $cloth= new BaseCloth("白布");
    $dyeing=new DyeingCloth($cloth->cloth());
    $stamp=new StampCloth($dyeing->dyeing());
    $cut=new CutCloth($stamp->stamp());
    echo $cut->cut();
?>


装饰器模式实现布匹加工。

<?php
    header("content-type:text/html;charset=utf8");
    /**
     * 装饰器模式完成布料的加工。动态、扩展性好。
     */
    class BaseCloth{         //布料的初始样子
        protected $content;
        public function __construct($con){
            $this->content=$con;
        }
        public function cloth(){
            return $this->content;
        }
    }
    class DyeingCloth extends BaseCloth{   //染色
        public function __construct(BaseCloth $cloth){
            $this->cloth=$cloth;
            $this->cloth();
        }
        public function cloth(){
            return $this->cloth->cloth()."  --->染上色";
        }
    }
    class StampCloth extends BaseCloth{   //印花
        public function __construct(BaseCloth $cloth){
            $this->cloth=$cloth;
            $this->cloth();
        }
        public function cloth(){
            return $this->cloth->cloth()."  --->印上花";
        }
    }
    class CutCloth extends BaseCloth{      //裁剪
        public function __construct(BaseCloth $cloth){
            $this->cloth=$cloth;
            $this->cloth();
        }
        public function cloth(){
            return $this->cloth->cloth()."  --->根据需求裁剪";
        }
    }


    //布料加工。
    $con=new CutCloth(new DyeingCloth(new BaseCloth("白布")));
    echo $con->cloth();
?>




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值