• php 装饰者模式


    装饰者模式

    现在出现这样一个场景:公司招聘人才,现在有很多继承person类的子类,如salePerson,ItPerson,sale+Itperson类等等;现在公司准备对能力不一样的人才提高工资收入。程序员恼火了,这种累有很多,我们需要一个个去修改代码,这是勤快人做的事,对于懒人还是多想想怎么解决这个鬼东西?于是装饰者模式百年诞生了,看代码如何实现这样的方式:

    abstract class person{
        public $_name;
        abstract function money();
    }
    //被装饰者
    class salePerson extends person{
        function __construct()
        {
            $this->_name = 'saler';
        }
        public function money()
        {
            return 100;
        }
    }
    //装饰者
    class ItPerson extends person{
        public $_person;
        function __construct(Person $person)
        {
            $this->_name = 'It';
            $this->_person = $person;
        }
        public function money()
        {
            return $this->_person->money() + 100;
        }
    }
    $salePerson = new salePerson();
    
    $saleItPerson = new ItPerson($salePerson);
    
    print $saleItPerson->money();

    装饰者和被装饰者必须是一样的类型,目的就是装饰者取代被装饰者。

    类的原则就是对扩展开发,对修改关闭。虽然装饰者模式好用,但不能项目中都用装饰者模式,这是一种浪费,造成太小类太多,装饰者模式适合裱花比较多的项目当中,如餐饮等,具体在哪里使用还是靠自己经验的积累,毕竟一个项目并非只用一个模式实现,往往是多重模式相结合实现的。

  • 相关阅读:
    CRM 安装过程 AD+SQL+CRM
    CRM系统新思维
    美团点评前端无痕埋点实践
    大数据平台的技术演化之路 诸葛io平台设计实例
    Dynamics 365 for Team Members Description
    Integrating SharePoint 2013 with ADFS and Shibboleth
    CRM 安全证书到期操作命令
    cmseasy CmsEasy_5.6_20151009 无限制报错注入(parse_str()的坑)
    Mlecms Getshell
    Discuz 5.x 6.x 7.x 前台SQL注入漏洞
  • 原文地址:https://www.cnblogs.com/happy-dream/p/6611351.html
Copyright © 2020-2023  润新知