您的位置:首页 > 编程语言 > C#

[C# 设计模式] Adapter - 适配器模式(两种)

2017-03-18 10:56 423 查看

Adapter - 适配器模式

  现实生活中,我们常用到适配器。

  你当前打开我这篇文章的笔记本电脑,电源的另一边不正连着一块适配器吗?

  你平时想将三口插座插进二口插座里面,不也需要一个适配器吗?

  整天插在插座上的手机充电头,不也是一个适配器吗?





目录

第一种:类适配器(使用继承)

第二种:对象适配器(使用委托)

抽象的 UML 类图

第一种:类适配器(使用继承)

  这里,我假设家用功率为 220v,经过适配器,输出为 18v,可供我的笔记本进行使用。

  类图



  Portal(入口) 类:只有一个方法 Input(),来表示输入的电流功率。

  IOutput(输出)接口:只有一个方法 Output(),来表示经过转换后输出的电流功率。

  Adapter(适配器)类:实现了 IOutput 接口。

  Portal.cs 类

/// <summary>
/// 入口
/// </summary>
class Portal
{
private readonly string _msg;

public Portal(string msg)
{
_msg = msg;
}

/// <summary>
/// 输入(电流)
/// </summary>
public void Input()
{
Console.WriteLine(_msg + " --> 18v。");
}
}


  

  IOutput.cs 接口

interface IOutput
{
/// <summary>
/// 输出(电流)
/// </summary>
void Output();
}


  Adapter.cs 类

/// <summary>
/// 适配器
/// </summary>
class Adapter : Portal, IOutput
{
public Adapter(string msg) : base(msg)
{
}

public void Output()
{
Input();
}
}


  Client.cs 类

class Client
{
static void Main(string[] args)
{
IOutput adapter = new Adapter("220v");
adapter.Output();

Console.Read();
}
}




  客户端在使用的过程中,我们只知道输出的结果即可,内部实现不需要理会。

第二种:对象适配器(使用委托)

  委托:自己不想做的事,交给第三方去做。

  类图



  Portal.cs 类

/// <summary>
/// 入口
/// </summary>
class Portal
{
private readonly string _msg;

public Portal(string msg)
{
_msg = msg;
}

public void Input()
{
Console.WriteLine(_msg + " --> 18v");
}
}


  Adapter.cs 类

class Adapter : Export
{
private readonly Portal _portal;

public Adapter(string msg)
{
_portal = new Portal(msg);
}

public override void Output()
{
_portal.Input();
}
}


  Export.cs 类

/// <summary>
/// 出口
/// </summary>
abstract class Export
{
public abstract void Output();
}


抽象的 UML 类图

  4 种角色:Adaptee(被适配),Adapter(适配者),Client(使用场景),Target(目标对象)。

  Adaptee(被适配):不是 -er 结尾的哦,之前的 Portal(入口)类作为被适配者。

  Adapter(适配者):作为 Adaptee 和 Target 的媒介,进行调节。

  Client(使用场景):一个调用的入口,以 Main() 作为入口函数。

  Target(目标对象):调节(适配)后的输出,之前的 IOutput 接口和 Export 类都是作为 Target 对象。



图:类适配器(使用继承)



图:对象适配器(使用委托)

C# 设计模式系列

  《Iterator - 迭代器模式:我与一份奥利奥早餐的故事

【博主】反骨仔

【原文】http://www.cnblogs.com/liqingwen/p/6560899.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: