设计模式学习之适配器模式(Adapter)

适配器模式属于结构型模式,结构型模式描述的是如何组合类或者对象以获得更大的结构。

适配器模式:

作用:将一个类或者程序的接口转换为另一个接口,以适应客户类的需求

实现要点:通过继承或者对象组合的方法实现,分别称为类适配器和对象适配器。又是一个我们平时经常不知不觉使用的设计模式。

代码:

     class TargetClass 
{
public void Upiple()
{
Console.WriteLine(
"It works well");
}
}
class classAdapter : TargetClass
{
public void Ipiple()
{
Console.WriteLine(
"通过类适配器实现U型口:");
base.Upiple();
}
}
class objectAdapter
{
TargetClass t1
= new TargetClass();
public void Ipiple()
{
Console.WriteLine(
"通过对象适配器实现U型口:");
t1.Upiple();
}
}
//------------------执行----------------------------
class Program
{
static void Main(string[] args)
{
//假如客户限于某种条件,只能使用I型口的水管,则可以用适配器实现调用U型口的水管
classAdapter adp1= new classAdapter();
objectAdapter adp2
= new objectAdapter();
adp1.Ipiple();
adp2.Ipiple();
Console.ReadLine();
}
}

posted @ 2008-11-17 18:01  MichaelChen  阅读(283)  评论(0编辑  收藏  举报