23个设计模式汇总_方便记忆

一、 适配器(Adapter)模式

适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作。    有人把这种模式叫做包装(Wrapper)模式

二、 类的Adapter模式的结构:

 

由图中可以看出,Adaptee类没有Request方法,而客户期待这个方法。为了使客户能够使用Adaptee类,提供一个中间环节,即类Adapter类,Adapter类实现了Target接口,并继承自Adaptee,Adapter类的Request方法重新封装了Adaptee的SpecificRequest方法,实现了适配的目的。

因为Adapter与Adaptee是继承的关系,所以这决定了这个适配器模式是类的。

该适配器模式所涉及的角色包括:

目标(Target)角色:这是客户所期待的接口。因为C#不支持多继承,所以Target必须是接口,不可以是类。
源(Adaptee)角色:需要适配的类。
适配器(Adapter)角色:把源接口转换成目标接口。这一角色必须是类。

Adapter模式的示意性的实现:

//  Class Adapter pattern -- Structural example  
using System;

// "ITarget"
interface ITarget
{
  // Methods
  void Request();
}

// "Adaptee"
class Adaptee
{
  // Methods
  public void SpecificRequest()
  {
    Console.WriteLine("Called SpecificRequest()" );
  }
}

// "Adapter" 类的Adapter模式
class Adapter : Adaptee, ITarget
{
  // Implements ITarget interface
  public void Request()
  {
    // Possibly do some data manipulation
    // and then call SpecificRequest
    this.SpecificRequest();
  }
}

//也可以写成 对象的适配器模式
class Adapter : Target
{
  // Fields
  private Adaptee adaptee = new Adaptee();
 
  // Methods
  override public void Request()
  {
    // Possibly do some data manipulation
    // and then call SpecificRequest
    adaptee.SpecificRequest();
  }
}


/// <summary>
/// Client test
/// </summary>
public class Client
{
  public static void Main(string[] args)
  {
    // Create adapter and place a request
    ITarget t = new Adapter();
    t.Request();
  }
}

猜你喜欢

转载自blog.csdn.net/lizhenxiqnmlgb/article/details/84989716