zoukankan      html  css  js  c++  java
  • 设计模式之装饰器模式

    简介:

    Decorator装饰器,就是动态地给一个对象添加一些额外的职责,该对象与装饰器对象需要实现同一个接口,装饰器在方法实现里调用目标对象的方法实现并加入额外的操作。

    使用场景:

    将复杂的功能细化,分散到不同的装饰器中,然后根据需要动态的组合这些功能。

    类图:

    示例代码:

    装饰器跟被目标对象都需实现的接口:

    public interface Component {
        public void operation();
    }

    真正的实现类:

    public class ConcreteComponent implements Component {
    
        @Override
        public void operation() {
            System.out.println("I am doing the real thing");
    
        }
    
    }

    装饰器A:

    public class DecoratorA implements Component {
    
        private Component component;
    
        public DecoratorA(Component component) {
            super();
            this.component = component;
        }
    
        @Override
        public void operation() {
            component.operation();
            System.out.println("I am doing the extra thing A");
        }
    
    }

    装饰器B:

    public class DecoratorB implements Component {
    
        private Component component;
    
        public DecoratorB(Component component) {
            super();
            this.component = component;
        }
    
        @Override
        public void operation() {
            component.operation();
            System.out.println("I am doing the extra thing B");
        }
    
    }

    客户端:

    public static void main(String[] args) {
            Component component = new DecoratorB(new DecoratorA(new ConcreteComponent()));
            component.operation();
    
        }

    运行结果:

    I am doing the real thing
    I am doing the extra thing A
    I am doing the extra thing B

  • 相关阅读:
    DBA操作常用命令
    DBA常用SQL
    安装下rlwrap
    destoon复制新模块的方法
    生成二维码
    布隆过滤
    Golang中的三个点
    Golang: 数组和切片
    Fabric的权限管理:Attribute-Based Access Control
    Node.js web发布到AWS ubuntu 之后,关闭Putty,Node 项目也随之关闭的解决办法
  • 原文地址:https://www.cnblogs.com/longzhaoyu/p/4211691.html
Copyright © 2011-2022 走看看