一.介绍
适配器模式(Adapter Pattern)。属于结构型模式。将一个类的接口转换成客户希望的另一个接口,Adapter模式使得原本因为接口不兼容而不能一起工作的那些类可以一起工作。
二.实现
客户调用Adaptee类的时候,希望Adaptee类可以提供一个指定名称的Request方法,而Adaptee类不能提供,这就需要提供一个中间适配类Adapter类,由Adapter类实现Request接口,并调用Adaptee类。Adapter适配类重新封装了Adaptee类的SpecificRequest方法,实现适配的目的。
//目标接口 public interface ITarget { void Request(); } //适配器 对象的适配器模式 public class Adapter : ITarget { private Adaptee adaptee = new Adaptee(); public void Request() { adaptee.SpecificRequest(); } } //适配器2 类的适配器模式 public class Adapter2 : Adaptee, ITarget { public void Request() { base.SpecificRequest(); } } //调用的类 public class Adaptee { public void SpecificRequest() { Console.WriteLine("SpecificRequest"); } } //调用 public static void Main(string[] args) { //适配器 ITarget adapter = new Adapter(); adapter.Request(); //适配器2 ITarget adapter2 = new Adapter2(); adapter2.Request(); }
三.总结
优点:
1.可以让任何两个没有关联的类一起运行。
2.可以在不修改原有代码的基础上来复用现有类,很好地符合 “开闭原则”。
3.增加了类的透明度和更好的灵活性。
缺点:
1.在类的适配器模式中,由于C#不支持多重继承,所以最多只能适配一个适配者类。
2.在类的适配器模式中,采用了类和接口的“双继承”实现方式,带来了不良的高耦合。