美文网首页
设计模式之装饰者模式

设计模式之装饰者模式

作者: 逍遥白亦 | 来源:发表于2021-01-09 23:23 被阅读0次

    1. 定义

    指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。

    2. 适用性

    以下情况下使用Decorator模式:

    • 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责
    • 处理那些可以撤销的职责
    • 当不能采用生成子类的方法进行扩充时

    3. 参与者

    • Component:定义一个对象接口,可以给这些对象动态地添加职责
    • ConcreteComponent:定义一个对象,可以给这个对象添加一些职责
    • Decorator:维持一个指向Component对象的指针,并定义一个与Component接口一致的接口
    • ConcreteDecorator:向组件添加职责

    4. 类图

    image

    5. 实现

    package decorator;
    
    public class DecoratorPattern {
        public static void main(String[] args) {
            Component p = new ConcreteComponent();
            p.operation();
            System.out.println("---------------------------------");
            Component d = new ConcreteDecorator(p);
            d.operation();
        }
    }
    
    //抽象构件角色
    interface Component {
        public void operation();
    }
    
    //具体构件角色
    class ConcreteComponent implements Component {
        public ConcreteComponent() {
            System.out.println("创建具体构件角色");
        }
    
        public void operation() {
            System.out.println("调用具体构件角色的方法operation()");
        }
    }
    
    //抽象装饰角色
    class Decorator implements Component {
        private Component component;
    
        public Decorator(Component component) {
            this.component = component;
        }
    
        public void operation() {
            component.operation();
        }
    }
    
    //具体装饰角色
    class ConcreteDecorator extends Decorator {
        public ConcreteDecorator(Component component) {
            super(component);
        }
    
        public void operation() {
            super.operation();
            addedFunction();
        }
    
        public void addedFunction() {
            System.out.println("为具体构件角色增加额外的功能addedFunction()");
        }
    }
    

    相关文章

      网友评论

          本文标题:设计模式之装饰者模式

          本文链接:https://www.haomeiwen.com/subject/elghaktx.html