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
  • 相关阅读:
    【原】【Git】EGit强制覆盖本地文件
    【EGit】The current branch is not configured for pull No value for key branch.master.merge found in config
    【转】【Egit】如何将eclipse中的项目上传至Git
    参加SAP VT项目有感
    2013_12_30 纪念
    2013 12 25 圣诞日
    gin系列-中间件
    gin系列- 路由及路由组
    gin系列-重定向
    gin系列-文件上传
  • 原文地址:https://www.cnblogs.com/baizhuang/p/10476249.html
Copyright © 2011-2022 走看看