一、定义
适配器模式:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
解释:适配器模式好比一个电源适配器,生活中房间内的电压是220v,但是你的很多用电器就不是220v,比如电脑、手机等等,这是需要电源适配器来调节电压,使用电源适配器充电的过程就相当于适配器模式。
二、UML类图、基本代码
基本代码:
class Target { public virtual void Request() { Console.WriteLine("commom request"); } } class Adaptee { public void SpecificalRequest() { Console.WriteLine("specifical Request"); } } class Adapter : Target { private Adaptee adptee = new Adaptee(); public override void Request() { adptee.SpecificalRequest(); } }
测试如下:
Target target = new Adapter(); target.Request();
三、举例说明
国内电压是220v,朋友从国外购买一家用电器的工作电压是110v,这算是一个特殊需求。此时就需要电源适配器供电工作。代码如下:
class Program { static void Main(string[] args) { China china = new Adapter(); china.Request(); Console.Read(); } } //国内供电 class China { public virtual void Request() { Console.WriteLine("the voltage is 220v"); } } //用电器供电特殊需求 class Foreign { public void SpecificalRequest() { Console.WriteLine("the voltage is 110v"); } } //电源适配器 class Adapter : China { private Foreign foreign = new Foreign(); public override void Request() { foreign.SpecificalRequest(); } }