[结构型(接口型模式)]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的关系。其类图如下所示:
![](http://images.cnblogs.com/cnblogs_com/winston/ada.JPG)
另外一种是在Adapter类中定义一个Adaptee类型的对象。通过借助Adaptee对象来实现Target接口内的方法。因此,Adapter和Adaptee之间是has-a的关系。其类图如下所示:
![](http://images.cnblogs.com/cnblogs_com/winston/hasa.JPG)
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();
}
}
假设存在已经开发好的类及其特定方法,但是在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();
}
}
相关文章推荐
- 九.结构型设计模式——Adapter Pattern(适配器模式)
- 结构型模式:适配器模式(Adapter Pattern)
- Java设计模式之结构型模式-适配器模式(Adapter)
- 结构型设计模式-适配器模式
- (结构型模式一)适配器模式
- 设计模式(结构型)之适配器模式(Adapter Pattern)
- 结构型模式之适配器模式实现
- 结构型模式-Adapter ( 适配器模式 )
- [设计模式笔记]二. 结构型模式--7.Adapter模式(适配器模式)(二)
- 设计模式(6) 结构型模式和适配器模式(ADAPTER)
- 对象结构型模式——适配器模式(adapter)
- 设计模式笔记(7)---适配器模式(结构型)
- 结构型模式之适配器模式(Adapter)
- 适配器模式——结构型模式
- java设计模式--结构型模式--适配器模式
- 适配器模式(Adapter Pattern)----------结构型模式
- 结构型模式之适配器模式(Adapter)
- Java设计模式——接口型模式:适配器模式
- 【设计模式学习笔记七】【结构型模式】【适配器模式(Adapter)】
- 设计模式--结构型--适配器模式