java设计模式——装饰模式

2017-10-16  本文已影响0人  TangBuzhi

装饰模式

1.定义:

动态的给一个对象添加一些额外的职责。就增加功能来讲,装饰模式比生成子类更为灵活。

2.使用场景:

3.UML图

4.详解:

装饰模式(Decorator Pattern)也称为包装模式(Wrapper Pattern),结构型设计模式之一,其使用一种对客户端透明的方式来动态的扩展对象的功能,同时它也是继承关系的一种替代方案之一。
代码举例:

public interface Sourceable {
        void method();
    }

    public static class Source implements Sourceable {
        @Override
        public void method() {
            System.out.println("this is original method");
        }
    }

    public static class SourceDecorator implements Sourceable {
        private Source source;

        public SourceDecorator(Source source) {
            this.source = source;
        }

        @Override
        public void method() {
            System.out.println("before decorator");
            source.method();
            System.out.println("after decorator");
        }
    }

测试代码:

public static void main(String[] args) {
        Source source = new Source();
        Sourceable decorator = new SourceDecorator(source);
        decorator.method();
        /**输出结果:
         before decorator
         this is original method
         after decorator
         */
    }

5.代码托管地址

装饰模式

上一篇 下一篇

猜你喜欢

热点阅读