C#实例解析适配器设计模式

[来源] 达内    [编辑] 达内   [时间]2013-03-06

将一个类的接口变成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够一起工作

  的适配器设计模式的文章。其中提到了把输入的电压转换成灯泡适合的电压,这样才能使灯泡正常工作。正巧,我也在学习设计模式,其中翻看了一下秦小波写的《设计模式与禅》这本书,其中提到了设计模式的定义为:

  将一个类的接口变成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够一起工作。

  适配器模式又叫变压器模式,也叫包装模式。

  这里作者举得例子并没有实现把一个接口或类转换到另外一个可以使用的类,仅仅是把输入参数做了判断,这是不是适配器模式我不予置评,下面贴出我实现的适配器模式。

  我们知道,中国的电压是220V,而日本的电压为110V,我们中国生产的电灯泡一般额定电压为220V,如果想要这个灯泡在日本能够正常工作就必须使用一个适配器,把110V电压转换成220V电压。

  定义接口代码如下:

  1.using System;

  2.using System.Collections.Generic;

  3.using System.Linq;

  4.using System.Text;

  5.

  6.namespace HelloWorld

  7.{

  8. ///

 

  9. /// 中国电接口

  10. ///

  11. public interface IChinaElectricity

  12. {

  13. ///

 

  14. /// 电压

  15. ///

  16. ///

  17. int Voltage();

  18. }

  19. ///

 

  20. /// 日本电接口

  21. ///

  22. public interface IJapanElectricity

  23. {

  24. ///

 

  25. /// 电压

  26. ///

  27. ///

  28. int Voltage();

  29. }

  30. ///

 

  31. /// 灯接口

  32. ///

  33. public interface IChinaLight

  34. {

  35. ///

 

  36. /// 发光

  37. ///

  38. ///

  39. string Light(int voltage);

  40. }

  41.}

  定义的类如下:

  1.using System;

  2.using System.Collections.Generic;

  3.using System.Linq;

  4.using System.Text;

  5.

  6.namespace HelloWorld

  7.{

  8. public class ChinaElectricity : IChinaElectricity

  9. {

  10. public int Voltage()

  11. {

  12. return 220;

  13. }

  14. }

  15.

  16. public class JapanElectricity : IJapanElectricity

  17. {

  18. public int Voltage()

  19. {

  20. return 110;

  21. }

  22. }

  23.

  24. public class ChinaLight : IChinaLight

  25. {

  26. ///

 

  27. /// 发光

  28. ///

  29. ///

  30. public string Light(int voltage)

  31. {

  32. if (voltage == 220)

  33. {

  34. return "我发光啦....";

  35. }

  36. else

  37. {

  38. return ("电压不正确,无法正常工作...");

  39. }

  40. }

  41. }

  42. ///

 

  43. /// 定义一个电压适配器

  44. ///

  45. public class ElectricityAdapter : IChinaElectricity

  46. {

  47. private int voltage = 0;

  48. private IJapanElectricity iJElectricity = null;

  49.

  50. public ElectricityAdapter(IJapanElectricity _baseElectricity)

  51. {

  52. iJElectricity = _baseElectricity;

  53. voltage = this.iJElectricity.Voltage();

  54. }

  55. public int Voltage()

  56. {

  57. return voltage + 110;

  58. }

  59. }

  60.}

资源下载