现在的位置: 首页 > 综合 > 正文

每天一个设计模式之Adapter

2013年10月04日 ⁄ 综合 ⁄ 共 1327字 ⁄ 字号 评论关闭

今天来看一个久闻大名,如雷贯耳,其实没啥~~

的设计模式:adapter~~

 

Motivation

 

想想现实世界中例子。我们每个人在使用数码相机时都会用到的东西,SD卡。当我们想把SD卡中的照片存入电脑时会怎么样呢?

现在好多笔记本都有SD卡接口,直接插进去就可以用了。

不过如果没有呢?我的本本就没有~~~(本本是爷给买的thinkpad,嘿嘿)

当然是使用读卡器了。将SD卡插入读卡器的一端,另一段的USB接口插入电脑即可。

读卡器就是一个adapter。它起了转换的功能,将电脑和SD卡这两个接口不同的东西连接到了一起。

Intent

  • Convert the interface of a class into another interface clients expect.
  • Adapter lets classes work together, that could not otherwise because of incompatible interfaces.

The classes/objects participating in adapter pattern:

  • Target - defines the domain-specific interface that Client uses.
  • Adapter - adapts the interface Adaptee to the Target interface.
  • Adaptee - defines an existing interface that needs adapting.
  • Client - collaborates with objects conforming to the Target interface.

现在我们来实践一个实际的例子:

一个client class,名为windows,它可以调用一个shape类,shape类实现了一个draw()用于画图。而圆形和方形类分别继承了shape类,都实现了各自的draw()。window类有如下语句:

public void initial(Shape s){

  this.s = s;

  s.draw();

}

这样就实现了画图。如果这时,我们获得了一个第三方类库,Triangle三角形。三角形没有继承shape类,所以不可以被window直接调用。同时它也没有draw(),只有display()。这时我们的选择是:1,修改window,让它可以接受三角class为输入参数。2,修改三角类,让它继承shape类。不过这不可能。3,创建一个adapter。

 

public class TriangleAdapter:Shape{

  private Triangle tri;

  public TriangleAdapter (Triangle tri){

    this.tri = tri;

  }

 

  private void draw(){

    tri.display(); //这里可以看到adapter实现起来是多么的简单

  }

这样window就可以不用任何更改的使用triangle了。最终通过target和adapter的转接,client实现了调用adaptee中的方法。

 

可以看到上例中,通过对Target的继承实现了adapter。而实现adapter的方法有两种:继承和代理。

 

 

抱歉!评论已关闭.