zoukankan      html  css  js  c++  java
  • 设计模式之装饰模式

    顾名思义,装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例

    1.需要装饰的接口

    package com.yun.base.design.decorator;
    
    public interface Sourceable {
        public void method(); 
    }

    2.需要装饰的方法 

    package com.yun.base.design.decorator;
    
    public class Source implements Sourceable {  
          
        @Override  
        public void method() {  
            System.out.println("the original method!");  
        }  
    }

    3.装饰器

    package com.yun.base.design.decorator;
    
    /**
     * 顾名思义,装饰模式就是给一个对象增加一些新的功能,
     * 而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例
     * 装饰器模式的应用场景:
     * 1、需要扩展一个类的功能。
     * 2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。)
     * 缺点:产生过多相似的对象,不易排错!
     * 
     * @author Administrator
     *
     */
    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!");  
        }  
    }  

    4.测试

    package com.yun.base.design.decorator;
    
    public class DecoratorTest {
        
        public static void main(String[] args) {  
            Sourceable source = new Source();  
            Sourceable obj = new Decorator(source);  
            obj.method();  
        }  
        
    }
  • 相关阅读:
    API下载文件
    c# 测试网络连接
    C# Word 插入签名图片
    c# word文档合并
    c# 文件筛选
    e
    基本初等函数(Basic elementary function)
    前端性能优化学习
    解决点击穿透的最佳实践
    ObjectARX通过选定的实体获取所有组名示例
  • 原文地址:https://www.cnblogs.com/yun965861480/p/7238298.html
Copyright © 2011-2022 走看看