設計模式系列6:適配器模式(Adapter Pattern)

定義

將一個類的接口轉換成客戶但願的另外一個接口,適配器模式使得本來因爲接口不兼容而不能一塊兒工做的那些類能夠一塊兒工做。    --《設計模式》GoF編程


UML類圖


使用場景

  1. 在遺留代碼複用,類庫遷移方面很是有用。
  2. 適配器模式要求咱們儘量地使用面向接口編程風格,這樣擴展性和可維護性比較好。


關鍵組成部分

1,目標角色(Target):定義Client使用的與特定領域相關的接口。設計模式

2,客戶角色(Client):與符合Target接口的對象協同。app

3,被適配角色(Adaptee):定義一個已經存在並已經使用的接口,這個接口須要適配。ide

4,適配器角色(Adapter):適配器模式的核心,它將對被適配Adaptee角色已有的接口轉換爲目標角色Target匹配的接口。對Adaptee的接口與Target接口進行適配。spa


C#代碼實現

using System;
 
namespace DoFactory.GangOfFour.Adapter.Structural
{
  /// <summary>

  /// MainApp startup class for Structural

  /// Adapter Design Pattern.

  /// </summary>

  class MainApp

  {
    /// <summary>

    /// Entry point into console application.

    /// </summary>

    static void Main()
    {
      // Create adapter and place a request

      Target target = new Adapter();
      target.Request();
 
      // Wait for user

      Console.ReadKey();
    }
  }
 
  /// <summary>

  /// The 'Target' class

  /// </summary>

  class Target

  {
    public virtual void Request()
    {
      Console.WriteLine("Called Target Request()");
    }
  }
 
  /// <summary>

  /// The 'Adapter' class

  /// </summary>

  class Adapter : Target

  {
    private Adaptee _adaptee = new Adaptee();
 
    public override void Request()
    {
      // Possibly do some other work

      //  and then call SpecificRequest

      _adaptee.SpecificRequest();
    }
  }
 
  /// <summary>

  /// The 'Adaptee' class

  /// </summary>

  class Adaptee

  {
    public void SpecificRequest()
    {
      Console.WriteLine("Called SpecificRequest()");
    }
  }
}

運行結果:設計

image

相關文章
相關標籤/搜索