接口型设计模式(Interface patterns)之adapter(适配器)

来源:互联网 发布:怎么把淘宝开通手机 编辑:程序博客网 时间:2024/06/08 15:28

接口型设计模式(Interface patterns)之adapter(适配器)


The intent of  ADAPTER  is to provide the interface that a client  expects while using the services of a class with a different  interface. 

适配器模式 的意图在于,使用不同接口的类所提供的服务为客户端提供它所期望的接口。

 


Like any adapter in the real world it is used to be an interface, a bridge between two objects.
In real world we haveadapters for power supplies, adapters for camera memory cards, and so on.
Probably everyone have seen some adapters for memory cards. If you can not plug in the camera memory
in your laptop you can use and adapter. You plug the camera memory in the adapter and the adapter in to laptop
slot. That's it, it's really simple.
  现实生活中的电源适配器、相机内存卡适配器等等,都是适配器模式的应用。

What about software development? It's the same. Can you imagine an situation when you have some class
expecting some type of object and you have an object offering the same features, but exposing a different interface?
Of course, you want to use both of them so you don't to implement again one of them, and you don't want to change
existing classes, so why not create an adapter.

The ADAPTER pattern lets you use an existing class to meet a client  class’s needs. When a client specifies its requirements in an interface, you can usually create a new class that implements the interface and 
subclasses an existing class
. This approach creates a
class adapter that translates a client’s calls into calls to the existing class’s methods. When a client does not specify the interface it requires, you may still be able to apply ADAPTER, creating a new client subclass that uses an instance of the existing class. This approach creates an object adapter that forwards a client’s calls to an instance of the existing class. This approach can be dangerous, especially if you don’t (or perhaps can’t)  override all the methods that the client might call.

适配器大多两种方式实现:

Objects Adapters - Based on Delegation

Class Adapters - Based on (Multiple) Inheritance


现实项目中,比如我们经常用到缓存服务器memcache 与redis,如何在这两者之间切换呢,我们可以先定义一个缓存标准接口(类似标准javax.cache),然后用适配器实现具体的缓存命令。

   笔记参考:

   [Java设计模式(第2版)].(Design.Patterns.in.Java).Steven.John.Metsker

   http://www.oodesign.com/adapter-pattern.html

    https://www.tutorialspoint.com/design_pattern/adapter_pattern.htm






扫一扫关注微信:


0 0