• 11、装饰器模式


    装饰器 Decorator 

    允许向一个现有的对象添加新的功能,同时又不改变其结构。这种设计类型属于结构性模式,它是作为现有类的一个包装

    这种设计模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整的前提下,提供额外的功能。

    意图:动态滴给一个对象添加一些额外的职责,就增加功能来说,装饰器相比于生成子类,更加灵活

    何使使用装饰器: 在不想增加子类的情况下,扩展类

    优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

    缺点:多层装饰比较复杂。

    使用场景: 1、扩展一个类的功能。 2、动态增加功能,动态撤销。

    //基础接口
    public interface Component {
        
        public void biu();
    }
    //具体实现类
    public class ConcretComponent implements Component {
    
        public void biu() {
            
            System.out.println("biubiubiu");
        }
    }
    //装饰类
    public class Decorator implements Component {
    
        public Component component;
        
        public Decorator(Component component) {
            
            this.component = component;
        }
        
        public void biu() {
            
            this.component.biu();
        }
    }
    //具体装饰类
    public class ConcreteDecorator extends Decorator {
    
        public ConcreteDecorator(Component component) {
    
            super(component);
        }
    
        public void biu() {
            
            System.out.println("ready?go!");
            this.component.biu();
        }
    }
    //使用装饰器
      Component component = new ConcreteDecorator(new ConcretComponent());
      component.biu();
    
      //console:
      ready?go!
      biubiubiu
  • 相关阅读:
    分页SQL 和Oracle 存储过程
    什么是SilverLight
    opendpi 源码分析(一)
    Multiway arrays
    循环链表
    轮询算法 这是一个印度人写的,学习下。 来自 codeproject
    Friday the Thirteenth
    通过命令行指定监听的IP和端口
    pthread_key_t
    贝叶斯网络 未学习前数据结构
  • 原文地址:https://www.cnblogs.com/bytecodebuffer/p/10476249.html
Copyright © 2020-2023  润新知