桥接模式和适配器模式的区别 [英] Difference between Bridge pattern and Adapter pattern

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

问题描述

桥接模式和适配器模式有什么区别?

What is the difference between the Bridge and Adapter patterns?

推荐答案

适配器使设计后的东西工作;Bridge 使它们工作在他们之前工作.[GoF, p219]"

"Adapter makes things work after they're designed; Bridge makes them work before they are. [GoF, p219]"

实际上,Adapter 模式在您拥有现有代码(无论是第三方代码还是内部代码)但不受您控制或无法更改以完全满足您需要的界面时非常有用它到.例如,我们有一个 SuperWeaponsArray,它可以控制一系列世界末日设备.

Effectively, the Adapter pattern is useful when you have existing code, be it third party, or in-house, but out of your control, or otherwise not changeable to quite meet the interface you need it to. For instance, we have a SuperWeaponsArray which can control a fine array of doomsday devices.

public class SuperWeaponsArray {
  /*...*/

  public void destroyWorld() {
    for (Weapon w : armedWeapons) {
      w.fire();
    }
  }
}

太好了.除非我们意识到我们的武器库中有一个核装置,它远远早于转换到武器界面.但我们真的很喜欢它在这里工作……那我们该怎么办……把它插进去!

Great. Except we realize we have a nuclear device in our arsenal that vastly predates the conversion to the Weapon interface. But we'd really like it to work here... so what do we do... wedge it in!

NukeWeaponsAdaptor - 基于我们的 Nuke 类,但导出了 Weapon 接口.亲爱的,现在我们肯定可以毁灭世界了.这似乎有点麻烦,但它使事情发挥作用.

NukeWeaponsAdaptor - based off of our Nuke class, but exporting the Weapon interface. Sweet, now we can surely destroy the world. It seems like bit of a kludge, but it makes things work.

桥接模式是你预先实现的东西——如果你知道你有两个正交的层次结构,它提供了一种解耦接口和实现的方法,这种方式你无法理解数量惊人的班级.假设您有:

The Bridge pattern is something you implement up front - if you know you have two orthogonal hierarchies, it provides a way to decouple the interface and the implementation in such a way that you don't get an insane number of classes. Let's say you have:

MemoryMappedFile 和 DirectReadFile 类型的文件对象.假设您希望能够从各种来源(可能是 Linux 与 Windows 实现等)读取文件.Bridge 可帮助您避免结束:

MemoryMappedFile and DirectReadFile types of file objects. Let's say you want to be able to read files from various sources (Maybe Linux vs. Windows implementations, etc.). Bridge helps you avoid winding up with:

MemoryMappedWindowsFile内存映射Linux文件直接读取Windows文件直接读取Linux文件

MemoryMappedWindowsFile MemoryMappedLinuxFile DirectReadWindowsFile DirectReadLinuxFile

这篇关于桥接模式和适配器模式的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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