zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    word count
    第三周作业:Visual Studio 2013
    第三周作业:读程序
    只有动手才能发现问题
    软件工程
    final个人阅读作业
    个人阅读作业7
    第一次个人项目修改
    结对编程项目总结(王开207, 唐彬170)
    个人博客作业3
  • 原文地址:https://www.cnblogs.com/baizhuang/p/10476249.html
Copyright © 2011-2022 走看看