代理、装饰器、适配器和桥接模式有何不同? [英] How do the Proxy, Decorator, Adapter, and Bridge Patterns differ?

查看:32
本文介绍了代理、装饰器、适配器和桥接模式有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究代理模式,在我看来,它与装饰器、适配器和桥接器模式非常相似.我误解了什么吗?有什么不同?为什么我要使用代理模式而不是其他模式?您过去如何在实际项目中使用它们?

I was looking at the Proxy Pattern, and to me it seems an awful lot like the Decorator, Adapter, and Bridge patterns. Am I misunderstanding something? What's the difference? Why would I use the Proxy pattern versus the others? How have you used them in the past in real world projects?

推荐答案

Proxy、Decorator、Adapter 和 Bridge 都是包装"类的变体.但它们的用途是不同的.

Proxy, Decorator, Adapter, and Bridge are all variations on "wrapping" a class. But their uses are different.

  • 代理可用于延迟实例化对象、隐藏调用远程服务或控制对对象的访问的事实.

  • Proxy could be used when you want to lazy-instantiate an object, or hide the fact that you're calling a remote service, or control access to the object.

装饰器也称为智能代理".当您想向对象添加功能但不是通过扩展该对象的类型时,可以使用它.这允许您在运行时执行此操作.

Decorator is also called "Smart Proxy." This is used when you want to add functionality to an object, but not by extending that object's type. This allows you to do so at runtime.

适配器用于当您有一个抽象接口,并且您想将该接口映射到另一个具有相似功能但具有不同接口的对象时使用.

Adapter is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.

Bridge 与 Adapter 非常相似,但是当您同时定义抽象接口和底层实现时,我们将其称为 Bridge.IE.您不适应某些遗留代码或第三方代码,您是所有代码的设计者,但您需要能够更换不同的实现.

Bridge is very similar to Adapter, but we call it Bridge when you define both the abstract interface and the underlying implementation. I.e. you're not adapting to some legacy or third-party code, you're the designer of all the code but you need to be able to swap out different implementations.

Facade 是一个或多个类的子系统的更高级别(读作:更简单)接口.假设您有一个需要多个对象来表示的复杂概念.对这组对象进行更改令人困惑,因为您并不总是知道哪个对象具有您需要调用的方法.那是编写 Facade 的时候了,它为您可以对对象集合执行的所有复杂操作提供高级方法.示例:学校部分的域模型,具有诸如 countStudents()reportAttendance()assignSubstituteTeacher() 等方法.

Facade is a higher-level (read: simpler) interface to a subsystem of one or more classes. Suppose you have a complex concept that requires multiple objects to represent. Making changes to that set of objects is confusing, because you don't always know which object has the method you need to call. That's the time to write a Facade that provides high-level methods for all the complex operations you can do to the collection of objects. Example: a Domain Model for a school section, with methods like countStudents(), reportAttendance(), assignSubstituteTeacher(), and so on.

这篇关于代理、装饰器、适配器和桥接模式有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆