C#设计模式编程中运用适配器模式结构实战演练

2019-12-26 17:40:10丽君

 Power.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatterns.AdapterPattern.Practical.ObjectAdapter
{
 public class Power
 {
  public void GetPower220V()
  {
   Console.WriteLine("从电源中得到220V的电压");
  }
 }
} 

 Adapter.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatterns.AdapterPattern.Practical.ObjectAdapter
{
 public class Adapter : ITarget
 {
  public Power _power;
  public Adapter(Power power)
  {
   this._power = power;
  }

  /// <summary>
  /// 得到想要的电压
  /// </summary>
  public void GetPower()
  {
   _power.GetPower220V();
   Console.WriteLine("得到手机的充电电压!");
  }
 }
} 

 Client.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatterns.AdapterPattern.Practical.ObjectAdapter
{
 public class Client
 {
  static void Main(string[] args)
  {
   Console.WriteLine("手机:");
   ITarget t = new Adapter(new Power());
   t.GetPower();
  }
 }
}

适配器模式的优缺点
在引言部分已经提出,适配器模式用来解决现有对象与客户端期待接口不一致的问题,下面详细总结下适配器两种形式的优缺点。
1.类的适配器模式:
优点:
可以在不修改原有代码的基础上来复用现有类,很好地符合 “开闭原则”
可以重新定义Adaptee(被适配的类)的部分行为,因为在类适配器模式中,Adapter是Adaptee的子类
仅仅引入一个对象,并不需要额外的字段来引用Adaptee实例(这个即是优点也是缺点)。
缺点:
用一个具体的Adapter类对Adaptee和Target进行匹配,当如果想要匹配一个类以及所有它的子类时,类的适配器模式就不能胜任了。因为类的适配器模式中没有引入Adaptee的实例,光调用this.SpecificRequest方法并不能去调用它对应子类的SpecificRequest方法。
采用了 “多继承”的实现方式,带来了不良的高耦合。
2.对象的适配器模式
优点:
可以在不修改原有代码的基础上来复用现有类,很好地符合 “开闭原则”(这点是两种实现方式都具有的)
采用 “对象组合”的方式,更符合松耦合。