zoukankan      html  css  js  c++  java
  • 设计模式学习笔记二十六:装饰器模式

    动机

    装饰器(Decorator)模式 也翻译为油漆工模式,另外也叫包装器(Wrapper)模式,包装器这个名字相对更贴切一些,属于对象结构型模式。它主要用来将给一个对象动态的添加一些额外的职责。

    典型应用

    • I/O流

    角色介绍

    • Component:通用对象接口,原始功能类和装饰器抽象类都要实现此接口才能保证构造函数参数的传递
    • ConcreteComponent:原始功能类,也就是被包装的类
    • Decorator:具体装饰器的父类,用来通过构造函数将具体的装饰器传入
    • ConcreteDecorator:具体的装饰器,继承Decorator

    UML结构图:

    代码实现

    1.通用对象接口,即Component:

    public interface Component {
        public void operation();
    }
    
    

    2.原始功能类,即ConcreteComponent:

    public class OriginalDecorator implements Component {
    
        @Override
        public void operation() {
            System.out.println("OriginalDecorator我是原始功能类……");
        }
    }
    
    

    3.装饰器基类,即Decorator:

    public abstract class Decorator implements Component{
        private Component component;
    
        public Decorator(Component component){
            this.component = component;
        }
    
        @Override
        public void operation() {
            component.operation();
        }
    }
    

    4.具体装饰器,即ConcreteDecorator:

    public class ConcreteDecoratorA extends Decorator {
    
        public ConcreteDecoratorA(Component component) {
            super(component);
        }
    
        @Override
        public void operation() {
            super.operation();
            System.out.println("在ConcreteDecoratorA进行修饰……");
        }
    
    }
    
    public class ConcreteDecoratorB extends Decorator {
    
        public ConcreteDecoratorB(Component component) {
            super(component);
        }
    
        @Override
        public void operation() {
            super.operation();
            System.out.println("在ConcreteDecoratorB进行修饰……");
        }
    }
    

    5.调用,TestDriver:

    public class Run {
        public static void main(String[] args) {
            new ConcreteDecoratorA(new ConcreteDecoratorB(new OriginalDecorator())).operation();
        }
    }
    

    6.输出

    OriginalDecorator我是原始功能类……
    在ConcreteDecoratorB进行修饰……
    在ConcreteDecoratorA进行修饰……
    
  • 相关阅读:
    Corosync+Pacemaker+DRBD+Mysql高可用HA配置
    高可用集群corosync+pacemaker之crmsh使用
    nfs+DRBD+corosync+pacemaker 实现高可用(ha)的nfs集群
    nginx匹配
    2011年的最后一篇
    Python自然语言处理学习笔记(66):7.7 小结
    Python自然语言处理学习笔记(65):7.6 关系抽取
    Python自然语言处理学习笔记(64): 7.5 命名实体识别
    Python自然语言处理学习笔记(67):7.8 扩展阅读
    Python自然语言处理学习笔记(68):7.9 练习
  • 原文地址:https://www.cnblogs.com/liushijie/p/4811981.html
Copyright © 2011-2022 走看看