您的位置:首页 > 其它

[结构型(接口型模式)]Adapter pattern 适配器模式

2008-05-13 15:50 274 查看
1 Adapter模式的作用

假设存在已经开发好的类及其特定方法,但是在reuse的时候和现有接口之间存在不协调,这时我们必须利用某种机制将已经存在的特定方法转化为另外能够接受的方法。这就是Adapter pattern。

(Adapter pattern是所有模式中最简单直观的模式了 :) )

2 Adapter模式的分类

Adapter模式的实现分为2种方式。

一种是建立一个inherented from Adaptee的类Adapter,当然由该类实现符合client要求的Target接口。因此,Adapter 和Adaptee之间是 is-a的关系。其类图如下所示:



另外一种是在Adapter类中定义一个Adaptee类型的对象。通过借助Adaptee对象来实现Target接口内的方法。因此,Adapter和Adaptee之间是has-a的关系。其类图如下所示:



3 代码实现:

Is-a Adapter pattern implementation:

public Interface Target

{

public void RequestMethod();

}

public class Adaptee

{

public void ExistedMethod()

{

Console.WriteLine("this is a original method");

}

}

public class Adatper:Target, Adaptee

{

public void RequestMethod()

{

Console.Write("the method is modified");

base.ExistedMethod();

}

}

Has-a Adapter pattern implementation:

public Interface Target

{

public void RequestMethod();

}

public class Adaptee

{

public void ExistedMethod()

{

Console.WriteLine("this is a original method");

}

}

public class Adatper:Target

{

protected Adaptee Adapteeobj;

public void RequestMethod()

{

Adapteeobj=new Adaptee();

Adapteeobj.ExistedMethod();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: