装饰模式(Decorator/Wrapper Pattern)

2017-12-10  本文已影响0人  1999c1b720cd

背景

在项目中运用该设计模式解决了问题,现对其进行总结,为以后思考问题和解决方案做备忘。

是什么

解决了什么问题

使用方法

调用者

    class Client {
        public static void main(String[] args){
            // one component
            Component component = new ConcreteComponent();
            // decor component with decorator
            Component decorator = new ConcreteDecorator(component);
            // send msg to decorator
            decorator.operation();
        }
    }

内部实现

    interface Component{
        void operation();
    }
    
    class ConcreteComponent implements Component {
        void operation(){
            // to sth.
        }
    }
    
    class ConcreteDecorator implements Component {
        Component component;
        
        ConcreteDecorator(Component component){
            this.component = component;
        }

        void operation(){
            // do sth. before 
            component.operation();
            // do sth. after
        }
    }

练习题

总结

参考

[1] 装饰模式

上一篇 下一篇

猜你喜欢

热点阅读