极速理解设计模式系列:6.适配器模式(Adapter Pattern)

简介:

四个角色:目标抽象类角色(Target)、目标对象角色(Adapter)、源对象角色(Adaptee)、客户端角色(Client)

        目标抽象类角色(Target):定义需要实现的目标接口

        目标对象角色(Adapter):调用另外一个源对象,并且转换(适配)为需要的目标对象。

        源对象角色(Adaptee):因为提供的功能不能满足现状,需要转换的源对象。

        客户端角色(Client):调用目标对象,对源对象进行加工。

         实现思路:首先取得需要转换的源对象,然后通过Adapter对源对象进行加工得到目标对象。

 类图:

        应用场景:在第三方类库中有一个源对象可以实现判断用户是否属于成人、是几个字的名字,但是需要的功能是显示用户信息,且不能更改第三方类库。

        分析:现在的系统中需要的是显示用户信息的功能,在这里我们通过适配器模式调用第三方的对象,在目标对象中显示用户信息处理,并提供接口给客户端。

        下面我们在控制台程序去演示一下如何使用Adapter Pattern:

        一、目标抽象类角色(Target)

    //Target(目标抽象类角色)
interface ITarget
{
void ShowInfo();
}

        二、目标对象角色(Adapter)

复制代码
    //Adapter(目标对象角色)
public class TargetInfoAdapter:ITarget
{
SourceInfo sinfo;
public TargetInfoAdapter(SourceInfo sourceinfo)
{
this.sinfo = sourceinfo;
}
public void ShowInfo()
{
Console.WriteLine(sinfo.Name
+ ":" + sinfo.Age + "" + sinfo.IsAdult() + " " + sinfo.NumberOfName());
}
}
复制代码

        三、源对象角色(Adaptee)

复制代码
    //Adaptee(源对象角色)
public class SourceInfo
{
public string Name { get; set; }
public int Age { get; set; }
public string IsAdult()
{
return Age > 17 ? "成年" : "未成年";
}
public string NumberOfName()
{
return Name.Length.ToString() + "个字名!";
}
}
复制代码

        四、客户端角色(Client)

复制代码
    //Client(客户端角色)
class Program
{
static void Main(string[] args)
{
//取得源对象
SourceInfo sinfo = new SourceInfo() { Name="小明",Age=15 };
//通过适配器转化源对象为目标对象。
ITarget target =new TargetInfoAdapter(sinfo);
target.ShowInfo();
Console.ReadLine();
}
}
复制代码

        如需源码请点击 AdapterPattern.rar 下载。


本文转自程兴亮博客园博客,原文链接:http://www.cnblogs.com/chengxingliang/archive/2011/09/15/2173195.html,如需转载请自行联系原作者


相关文章
|
6月前
|
设计模式
设计模式8 - 适配器模式【Adapter Pattern】
设计模式8 - 适配器模式【Adapter Pattern】
23 0
|
4月前
|
设计模式 Java 关系型数据库
认真学习设计模式之适配器模式(Adapter Pattern)/包装器模式
认真学习设计模式之适配器模式(Adapter Pattern)/包装器模式
58 0
|
Java 程序员 API
结构型模式 - 适配器模式(Adapter Pattern)
结构型模式 - 适配器模式(Adapter Pattern)
|
设计模式 Java Android开发
从零开始学设计模式(六):适配器模式(Adapter Pattern)
前面的几篇文章分别介绍了设计模式中的创建型设计模式,它们分别是:
399 0
从零开始学设计模式(六):适配器模式(Adapter Pattern)
|
设计模式 C#
【愚公系列】2021年12月 二十三种设计模式(六)-适配器模式(Adapter Pattern)
【愚公系列】2021年12月 二十三种设计模式(六)-适配器模式(Adapter Pattern)
102 0
【愚公系列】2021年12月 二十三种设计模式(六)-适配器模式(Adapter Pattern)
|
数据库 C#
C#设计模式之六适配器模式(Adapter Pattern)【结构型】
原文:C#设计模式之六适配器模式(Adapter Pattern)【结构型】 一、引言   从今天开始我们开始讲【结构型】设计模式,【结构型】设计模式有如下几种:适配器模式、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式。
1516 0