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

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

问题描述

桥接和适配器模式有什么区别?哪里可以使用每个模式?

解决方案

适配器使设计工作成功后,Bridge使它们在。[GoF,p219]



有效地,适配器模式在您具有现有代码,无论是第三方还是内部,但无法控制时都很有用,否则不可更改,以完全满足您需要的界面。例如,我们有一个SuperWeaponsArray,它可以控制一个精细的末日设备阵列。

  public class SuperWeaponsArray {
/*...*/

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

除了我们意识到我们在我们的武器库中有一个核装置,这远远超过了到武器界面的转换。但是我们真的希望在这里工作...所以我们做什么...楔入它!



NukeWeaponsAdaptor - 基于我们的Nuke类,但导出了Weapon界面。甜蜜,现在我们肯定会毁灭世界。这似乎是一个垃圾,但它使事情发挥作用。






如果你知道你有两个正交的层次结构,它提供了一种方法来解耦接口和实现,使得你不会得到疯狂数量的类。假设你有:



MemoryMappedFile和DirectReadFile类型的文件对象。假设您想要从各种来源读取文件(也许Linux与Windows实现等)。 Bridge帮助您避免清理:



MemoryMappedWindowsFile
MemoryMappedLinuxFile
DirectReadWindowsFile
DirectReadLinuxFile


What is the difference between the Bridge and Adapter patterns? Where i can use each pattern?

解决方案

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

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 - 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 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 MemoryMappedLinuxFile DirectReadWindowsFile DirectReadLinuxFile

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

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