我们什么时候需要适配器模式? [英] when do we need Adapter pattern?

查看:135
本文介绍了我们什么时候需要适配器模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们什么时候需要去适配器模式?如果可能,给我一个适合这种模式的真实世界的例子...

When do we need to go for Adapter pattern? If possible give me a real world example that suits that pattern...

推荐答案

我在一个需要与外部DVR。在大多数情况下,所有DVR具有相同的基本功能:从某个视频源开始录制;停止录音从一定时间开始播放;停止播放等。

I worked on a system which needed to interface with external DVRs. For the most part, all DVRs have the same basic functionality: start recording from a certain video source; stop recording; start playback from a certain time; stop playback, etc.

每个DVR制造商提供了一个软件库,允许我们编写代码来控制他们的设备(为了讨论,我会参考作为SDK)。即使每个SDK都提供了所有基本功能的API,但它们都不一样。这是一个非常粗略的例子,但是你会得到这样的想法:

Every DVR manufacturer provided a software library, allowing us to write code to control their device (for sake of this discussion, I'll refer to it as the SDK). Even though every SDK provided APIs for all the basic functionality, none of them were quite the same. Here's a very rough example, but you get the idea:


  • BeginPlayback(DateTime startTime);

  • StartPlayback(long startTimeTicks);

  • 播放(string startDate,string startTime);

我们的软件需要能够与所有DVR进行交互。因此,不是为每个不同的SDK编写可怕的开关/案例,我们创建了我们自己的通用IDVRController接口,并将所有系统代码写入该接口:

Our software needed to be able to interact with all DVRs. So instead of writing horrible switch/cases for each different SDK, we created our own common IDVRController interface, and wrote all of our system code to that interface:


  • 播放(DateTime startTime);

然后,我们为每个SDK编写了一个不同的适配器实现,所有这些实现了我们的IDVRController接口。我们使用一个配置文件来指定系统将连接到的DVR的类型,以及一个Factory模式来实例化该DVR的IDVRController的正确实现者。

We then wrote a different adapter implementation for each SDK, all of which implemented our IDVRController interface. We used a config file to specify the type of DVR the system would connect to, and a Factory pattern to instantiate the correct implementer of IDVRController for that DVR.

,适配器模式使我们的系统代码更简单:我们总是编码为IDVRController。它允许我们为部署后的新SDK推出适配器(我们的工厂使用反射来实例化正确的IDVRController实例)。

In that way, the adapter pattern made our system code simpler: we always coded to IDVRController. And it allowed us to roll out adapters for new SDKs post-deployment (our Factory used reflection to instantiate the correct IDVRController instance).

这篇关于我们什么时候需要适配器模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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