世外桃源

C#、Asp.net相关技术

导航

C#设计模式读书笔记之适配器模式

Posted on 2006-07-14 03:28  佚名  阅读(245)  评论(0编辑  收藏  举报
适配器模式负责在用户需求接口与不同的实现类之间的转换。如果客户需要某个类的服务而这个服务是这个类用不同的的接口提供的,那么就可以用适配器模式为客户提供一个期望的接口。分为两种情况:
        1、类适配器,模式原型的实现方法是,定义或获取一个需求的接口,包含一个或多个需求的方法,定义一个适配器类,继承于接口和实现接口需求的外部类,将客户的需求传递给实现需求的外部类,即达到了本模式的要求。
这是摘自吕老师的大作的代码,够精典的。
 1using System;
 2
 3// "ITarget"
 4interface ITarget
 5{
 6  // Methods
 7  void Request();
 8}

 9
10// "Adaptee"
11class Adaptee
12{
13  // Methods
14  public void SpecificRequest()
15  {
16    Console.WriteLine("Called SpecificRequest()" );
17  }

18}

19
20// "Adapter"
21class Adapter : Adaptee, ITarget
22{
23  // Implements ITarget interface
24  public void Request()
25  {
26    // Possibly do some data manipulation
27    // and then call SpecificRequest
28    this.SpecificRequest();
29  }

30}

31
32/**//// <summary>
33/// Client test
34/// </summary>

35public class Client
36{
37  public static void Main(string[] args)
38  {
39    // Create adapter and place a request
40    ITarget t = new Adapter();
41    t.Request();
42  }

43}

       2、对象适配器,如果没有定义一个接口,我们也可以使用适配器模式,这就是用对象适配器模式,定义一个类,定义一个可重写的虚方法,实现一个继承于需求类的适配器类,在这个类内部实例化一个能满足需求类的外部类,重写需求方法,将外部类方法传递给需求方法。
 1using System;
 2
 3// "Target"
 4class Target
 5{
 6  // Methods
 7  virtual public void Request()
 8  {
 9    // Normal implementation goes here
10  }

11}

12
13// "Adapter"
14class Adapter : Target
15{
16  // Fields
17  private Adaptee adaptee = new Adaptee();
18
19  // Methods
20  override public void Request()
21  {
22    // Possibly do some data manipulation
23    // and then call SpecificRequest
24    adaptee.SpecificRequest();
25  }

26}

27
28// "Adaptee"
29class Adaptee
30{
31  // Methods
32  public void SpecificRequest()
33  {
34    Console.WriteLine("Called SpecificRequest()" );
35  }

36}

37
38/**//// <summary>
39/// Client test
40/// </summary>

41public class Client
42{
43  public static void Main(string[] args)
44  {
45    // Create adapter and place a request
46    Target t = new Adapter();
47    t.Request();
48  }

49}

       适配器模式加大对现在的代码的重用。通过适配器能在不同的接口之间实现翻译的功能。同时对于没有实现接口的需求,也能通过对象适配器建立一个转交需求的作用。