适配器模式

适配器模式:

 将一个类的接口转换为客户希望的另外一种接口,Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

注意:适配器模式,一般应用于 无法改变原有设计和代码的情况下,才考虑适配。(事后控制不如事中控制,事中控制不如事前控制。)

一、UML结构图

 

 

二、示例代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 /*
 7  * 示例:例如 日常生活中的电压,中国220V,欧美110V,现在需要一个将中国电压转换为36V的适配器。
 8  * 
 9  */
10 namespace 适配器模式
11 {
12     class Program
13     {
14         static void Main(string[] args)
15         {
16             //用一个中国电压的适配器
17             Target_36V target = new Adepter_China();
18             target.Get36V();
19 
20             Console.Read();
21         }
22     }
23 
24     /// <summary>
25     /// 定义一个对外的服务类,插座
26     /// Target:对应UML中的客户目标Target
27     /// </summary>
28     public  class Target_36V
29     {
30         public virtual void Get36V()
31         {
32             Console.WriteLine("输出36V电压!");
33         }
34     }
35 
36     /// <summary>
37     /// 中国电压适配器,若需要欧美电压适配器,扩展适配器
38     /// </summary>
39     public class Adepter_China:Target_36V
40     {
41         private Adeptee_China m_AdepteeChina;
42         public Adepter_China()
43         {
44             m_AdepteeChina = new Adeptee_China();
45         }
46 
47         /// <summary>
48         /// 适配器转换
49         /// </summary>
50         public override void Get36V()
51         {
52             Console.WriteLine(string.Format("正在将{0}转换为36V...",m_AdepteeChina.MyDY()));
53 
54             base.Get36V();
55         }
56     }
57 
58 
59     public class Adeptee_China
60     {
61         public int MyDY()
62         {
63             Console.WriteLine("我是中国电压,220V");
64             return 220;
65         }
66     }
67 }
将中国电压220V转换为36V

 

三、应用

1、DataAdapter 就是一个很好的适配器模式

由于数据来源可能是Oracle、SQLServer,也可能是Access、DB2等等。

DataAdapter

    >通过Fill:更改了DataSet中的数据,更好的与数据源数据相匹配

   >通过Update:更改了数据源中的数据与DataSet中的数据相匹配。

 

 

 

posted @ 2019-12-02 16:38  秋飘  阅读(140)  评论(0编辑  收藏  举报