Decorator-装饰器模式 #################### .. note:: dynamically adds/overrides behaviour in an existing method of an object. 1. 装饰器类和原始类继承同样的父类,这样我们可以对原始类“嵌套”多个装饰器类 2. 装饰器类是对功能的增强,这也是装饰器模式应用场景的一个重要特点 例-对 FileInputStream 嵌套了两个装饰器类让它既支持缓存读取,又支持基本读取数据:: InputStream in = new FileInputStream("xxx.txt"); InputStream bin = new BufferedInputStream(in); DataInputStream din = new DataInputStream(bin); int data = din.readInt(); 与代理模式的区别 ================ :: 1. 代理模式中,代理类附加的是跟原始类无关的功能,而在装饰器模式中,装饰器类附加的是跟原始类相关的增强功能 2. 装饰器模式还有一个特点,那就是可以对原始类嵌套使用多个装饰器 为了满足这个应用场景,在设计的时候,装饰器类需要跟原始类继承相同的抽象类或者接口 // 下面是评论 3. Decorator关注为对象动态的添加功能, Proxy关注对象的信息隐藏及访问控制 4. Decorator体现多态性, Proxy体现封装性 参考 ==== * The Decorator Pattern In Go: https://levelup.gitconnected.com/the-decorator-pattern-in-go-66ed951b0f7c * Differences between Proxy and Decorator Pattern: https://stackoverflow.com/questions/18618779/differences-between-proxy-and-decorator-pattern