深入设计模式(三)——适配器模式

一、适配器设计模式介绍

      适配器模式,将一个类装换成客户期望的另外一个接口。Adapter模式使用的原本由于接口不兼容而不能茉莉花物那些可以一起工作。

二、解决的问题

      1、使用第三方组件,而这个组件的接口与目前系统接口不兼容(如方法与系统方法不一致等),可以使用适配器模式解决接口不兼容问题。

      2、使用早前项目一些有用的类,可以用适配器模式解决现有接口与原有对象接口不兼容问题。

三、生活中的例子

     适配器模式允许将一个类的接口转换成客户期望的另一个接口,使用原本由于接口不兼容而不能一起工作的类可以一起工作。扳手提供了一个适配器的例子。一个孔套在棘齿上,棘齿的每个边的尺寸是相同的。在美国典型的连长为1/2和1/4。显然,如果不使用一个适配器的话,1/2的棘齿不能适合1/4的孔。一个1/2到1/4的适配器具有一个1/2的阴槽来套上一个1/2的齿,同时有一个1/4的阳槽来卡入1/4的扳手。

四、适配器分析

    1.适配器模式结构

       深入设计模式(三)——适配器模式_第1张图片

     2.代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 适配器模式
 8 {
 9     /// <summary>
10     /// 客户期待的接口或者抽象类Target
11     /// </summary>
12    public abstract class Target
13     {
14        public abstract void Request();
15     }
16 }
客户期待的接口或者抽象类Target
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 适配器模式
 8 {
 9     /// <summary>
10     /// 要适配的类Adaptee,也就是与期望调用接口不相符的类
11     /// </summary>
12    public class Adaptee
13     {
14        public void SpecificReques() {
15            Console.WriteLine("执行要适配类的特殊请求方法");
16        }
17     }
18 }
要适配的类Adaptee,也就是与期望调用接口不相符的类
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 适配器模式
 8 {
 9    public  class Adapter:Target
10     {
11        private Adaptee adaptee;
12         public override void Request()
13         {
14             if (adaptee == null) {
15                 adaptee = new Adaptee();
16             }
17             adaptee.SpecificReques();
18         }
19     }
20 }
适配器类Adapter,把源接口转换成目标接口,包行变量adaptee
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 适配器模式
 8 {
 9    /// <summary>
10    /// 适配器模式,将一个类装换成客户期望的另外一个接口。Adapter模式使的原本由于接口不兼容而不能工作的那些类可以一起工作
11    ///  解决的问题
12    ///     1.使用第三方组件,而这个组件的接口与目前系统接口不兼容(如方法与系统方法不一致等),可以使用适配器模式解决接口不兼容问题。
13    ///     2.使用早前项目一些有用的类,可以用适配器模式解决现有接口与原有对象接口不兼容问题。
14    /// </summary>
15     class Program
16     {
17         static void Main(string[] args)
18         {
19             Target target = new Adapter();
20             target.Request();
21             Console.ReadKey();
22         }
23     }
24 }
客户端代码

 

你可能感兴趣的:(适配器模式)