Java中“装饰模式”和“代理模式”有啥区别( 二 )

现在你已经进化成了穿好鞋的拳击手了
public class Test { public static void main(String args) { Boxer realBoxer = new BoxerImpl(); BoxerInReallyFastShoes boxerInReallyFastShoes = new BoxerInReallyFastShoes(realBoxer); Boxer Agent = new Agent(boxerInReallyFastShoes); System.out.println("准备比赛!"); boxerInReallyFastShoes.moveFast(); Agent.Fight(); System.out.println("比赛结束"); }}Java中“装饰模式”和“代理模式”有啥区别

最终,在你的鞋子的增强下,你在面对任何比你跑的快的选手都能冷静面对了

为让自己的能力增强,使得增强后的自己能够使用更多的方法,拓展在自己基础之上的功能的,就是装饰器模式
所以话说回来,装饰器模式与代理模式的区别就在于(其实强行区分这两者的区别并没有太多意义,毕竟他们之间的边界确实比较模糊):
1.两者都是对类的方法进行扩展,但装饰器模式强调的是增强自身,在被装饰之后你能够在被增强的类上使用增强后的功能。增强后你还是你,只不过能力更强了而已;而代理模式则强调要让别人帮你去做一些本身与你业务没有太多关系的职责(记录日志、设置缓存)。代理模式是为了实现对象的控制,因为被代理的对象往往难以直接获得或者是其内部不想暴露出来。
2.在Java中使用装饰器模式的源码有IO流:
InputStream inputStream = new InputStream() { @Override public int read() throws IOException { return 0; } }; BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);//增强了原本InputStream的功能3.使用代理模式的例子就很多了,比如Spring里面的AOP,Interceptor等等需要在方法前后进行调用来增强的:
public interface InvocationHandler { public Object invoke(Object proxy, Method method, Object args) throws Throwable;}
■网友
这个在GOF的设计模式一书里面的结构型设计模式,最后讲的很清楚了,现在贴出啦。
Like Decorator, the Proxy pattern composes an object and provides an identical in- terface to clients. Unlike Decorator, the Proxy pattern is not concerned with attaching or detaching properties dynamically, and it\u0026#39;s not designed for recursive composition. Its intent is to provide a stand-in for a subject when it\u0026#39;s inconvenient or undesirable to access the subject directly because, for example, it lives on a remote machine, has restricted access, or is persistent.
In the Proxy pattern, the subject defines the key functionality, and the proxy provides (or refuses) access to it. In Decorator, the component provides only part of the functionality, and one or more decorators furnish the rest. Decorator addresses the situation where an object\u0026#39;s total functionality can\u0026#39;t be determined at compile time, at least not conveniently. That open-endedness makes recursive composition an essential part of Decorator. That isn\u0026#39;t the case in Proxy, because Proxy focuses on one relationship—between the proxy and its subject—and that relationship can be expressed statically.


推荐阅读