惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Jina AI
Jina AI
Recent Announcements
Recent Announcements
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
A
About on SuperTechFans
Vercel News
Vercel News
博客园 - 【当耐特】
爱范儿
爱范儿
Blog — PlanetScale
Blog — PlanetScale
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
D
Docker
博客园 - 叶小钗
The Cloudflare Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
H
Help Net Security
I
InfoQ
博客园 - 三生石上(FineUI控件)
博客园 - Franky
Microsoft Azure Blog
Microsoft Azure Blog
The GitHub Blog
The GitHub Blog
大猫的无限游戏
大猫的无限游戏
MongoDB | Blog
MongoDB | Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报

博客园 - 佚名

SqlCommand执行带GO的SQL脚本文件 TreeList之Extjs篇 XtreTreeList使用扎记(四) TreeList使用扎记(3) XtraTreeList使用扎记(2) TreeView节点快速访问之道 看了感触很深的一个贴子 XtraTreeList使用扎记(1) 勇气宣言 搞笑的段子 特别的一天 C#设计模式读书笔记之合成模式 C#设计模式读书笔记(1) Vs2003多窗口下的复杂数据传递 OWC中双刻度图表的实现 男人25岁前必须明白的21个道理!!! 关于Excel中Merge单元格 NET下XML的访问 ADO.NET技术内幕疑点之一
C#设计模式读书笔记之适配器模式
佚名 · 2006-07-14 · via 博客园 - 佚名

适配器模式负责在用户需求接口与不同的实现类之间的转换。如果客户需要某个类的服务而这个服务是这个类用不同的的接口提供的,那么就可以用适配器模式为客户提供一个期望的接口。分为两种情况:
        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}

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