zoukankan      html  css  js  c++  java
  • 23种设计模式之装饰模式代码实例

    装饰对象和被装饰对象实现同一个接口

    装饰对象持有被装饰对象的实例,给被装饰模式增添一些新的功能。

        public interface Sourceable {  
            public void method();  
        }  
    public class Source implements Sourceable {  
      
        @Override  
        public void method() {  
            System.out.println("the original method!");  
        }  
    }
        public class Decorator implements Sourceable {  
          
            private Sourceable source;  
              
            public Decorator(Sourceable source){  
                super();  
                this.source = source;  
            }  
            @Override  
            public void method() {  
                System.out.println("before decorator!");  
                source.method();  
                System.out.println("after decorator!");  
            }  
        }  
    public class DecoratorTest {  
      
        public static void main(String[] args) {  
            Sourceable source = new Source();  
            Sourceable obj = new Decorator(source);  
            obj.method();  
        }  
    }

    输出:

    before decorator!
    the original method!
    after decorator!

    应用场景:

    1、需要增加一个类的对象。

    2、动态的为一个对象增加功能,且不影响原有的功能。

  • 相关阅读:
    Linux操作系统(二)
    匿名函数和内置函数
    BeautifulSoup
    Robots协议
    列表和生成器表达式
    迭代器
    排序总结
    图论专题笔记
    Trie树的二三事QWQ
    二分答案经典入门题:)
  • 原文地址:https://www.cnblogs.com/longhaolove/p/7887523.html
Copyright © 2011-2022 走看看