我正在查看代理模式,对我来说,它看起来非常像装饰器、适配器和桥接模式。我是不是误解了什么?有什么不同?为什么我要使用代理模式而不是其他模式?在过去的实际项目中,您是如何使用它们的?


当前回答

Design pattern is not mathematics, it is combination of art and software engineering. There is nothing like for this requirment you have to use proxy, bridge etc. Design patterns are created to solve the problems. If you anticipate a design problem, then use it. Based on experience, you will come to know for specific problem, which pattern to use. If you are good in solid design principles, you would have implemented design pattern without knowing it is pattern. Common example is statergy and factory patterns

因此,更多地集中在坚实的设计原则,干净的编码原则和ttd

其他回答

Design pattern is not mathematics, it is combination of art and software engineering. There is nothing like for this requirment you have to use proxy, bridge etc. Design patterns are created to solve the problems. If you anticipate a design problem, then use it. Based on experience, you will come to know for specific problem, which pattern to use. If you are good in solid design principles, you would have implemented design pattern without knowing it is pattern. Common example is statergy and factory patterns

因此,更多地集中在坚实的设计原则,干净的编码原则和ttd

在使用web服务时,我经常使用它。代理模式可能应该重命名为更实用的东西,比如“包装器模式”。我也有一个库,是一个代理到MS Excel。它使自动化Excel变得非常容易,而不必担心背景细节,如安装了什么版本(如果有的话)。

它们非常相似,而且它们之间的线条是灰色的。我建议您阅读c2 wiki中的代理模式和装饰器模式条目。

那里的条目和讨论相当广泛,也链接到其他相关文章。顺便说一下,c2 wiki在了解不同模式之间的细微差别时非常有用。

总结c2项,我认为装饰器添加/更改行为,但代理与访问控制(延迟实例化,远程访问,安全等)有更多关系。但正如我所说,它们之间的界线是灰色的,我看到对代理的引用很容易被视为装饰器,反之亦然。

正如Bill的回答所说,它们的用例是不同的。

它们的结构也是如此。

Proxy and Decorator both have the same interface as their wrapped types, but the proxy creates an instance under the hood, whereas the decorator takes an instance in the constructor. Adapter and Facade both have a different interface than what they wrap. But the adapter derives from an existing interface, whereas the facade creates a new interface. Bridge and Adapter both point at an existing type. But the bridge will point at an abstract type, and the adapter might point to a concrete type. The bridge will allow you to pair the implementation at runtime, whereas the adapter usually won't.

所有这四种模式都涉及到用外部对象/类包装内部对象/类,因此它们在结构上非常相似。我将通过目的来概述不同之处:

代理将访问从外部封装到内部。 装饰器用外部修改或扩展内部的行为。 适配器转换接口从内部到外部。 桥将行为的不变部分(外部)与变量或平台依赖部分(内部)分开。

通过内外物体之间的界面变化:

在代理接口中是相同的。 在Decorator接口中是相同的。 在适配器接口形式上不同,但实现相同的目的。 桥接接口在概念上是不同的。