• 设计模式学习(三)、装饰者模式


    1装饰者模式的概念:

    动态的将责任附加到对象上。想要扩充功能,装饰者提供有利于继承的另一种选择。

    2.装饰者模式的结构图

    3.装饰者模式角色说明

    组件(component)角色:定义ConcreteComponent和Decorator类要实现的方法,简单来说如果一个类继承于该类就具有装饰或被装饰能力。
    具体组件(ConcreteComponent)角色:让Decorator对象为自己添加功能。
    抽象装饰者(Decorator)角色:装饰者共同实现的类。
    具体装饰者(ConcreteDecorator)角色:具有特定装饰功能的类,用来装饰ConcreteComponent类。

    4.装饰者模式的实现

    <?php
    /**
     * 装饰者模式实例
     */
    //抽象组件
     abstract Class Component
    {
        public abstract  function operation();
    }
    
    //具体组件
    class ConcreteComponent extends  Component
    {
        public function operation()
        {
            echo 'it is concreteComponent';
        }
    }
    
    //抽象装饰者
    abstract class Decorator extends  Component
    {
    
    }
    //抽象装饰者
    
    class ConcreteDecorator1 extends  Component
    {
        public $component;
        public function __construct($component)
        {
            $this->$component = $component;
        }
        public function operation(){
           echo  $this->component->operation().'add concreteDecorator1';
        }
    }
    //抽象装饰者
    
    class ConcreteDecorator2 extends  Component
    {
        public $component;
        public function __construct($component)
        {
            $this->$component = $component;
        }
        public function operation(){
            echo  $this->component->operation().'add concreteDecorator2';
        }
    }
    
    //客户端使用
    $c = new ConcreteComponent();
    $d1 = new ConcreteDecorator1($c);
    $d2 = new ConcreteDecorator2($d1);
    $p->operation();
    
     
  • 相关阅读:
    .netcore下Dapper helper类
    C#各版本新增加功能(系列文章)
    MySQL 查询连续登陆7天以上的用户
    MySQL 8.0版本 自动排序函数dense_rank() over()、rank() over()、row_num() over()用法和区别
    MYSQL 查看锁的方式
    MYSQL 回表查询原理,利用联合索引实现索引覆盖
    ES查询某个字段分词结果
    maven 安装和配置
    Java 注解
    Java 异常
  • 原文地址:https://www.cnblogs.com/huixuexidezhu/p/5972249.html
Copyright © 2020-2023  润新知