设计模式学习总结(七)适配器模式(Adapter)
适配器模式主要是通过适配器来实现接口的统一,如要实现国内手机在国外充电,则需要在不同的国家采用不同的适配器来进行兼容!
一、示例展示:
以下例子主要通过给笔记本电脑添加类似手机打电话和发短信的功能来详细演示适配器模式的应用!
对象适配器:
1. 创建抽象类:Handphone
public abstract class Handphone { public abstract void Dail(); public abstract void SendMessage(); }
2. 创建抽象类:Laptop
public abstract class Laptop { public abstract void Working(); }
3. 创建具体类:AppleLaptop
public class AppleLaptop : Laptop { public override void Working() { Console.WriteLine("Working using laptop!"); } }
4. 创建适配器类:
public class AppleLatopAdapter : Handphone { //Keep the reference of Laptop Laptop laptop; public AppleLatopAdapter(Laptop laptop) { this.laptop = laptop; } public void Working() { laptop.Working(); } public override void SendMessage() { Console.WriteLine("My apple laptop can send message now!"); } public override void Dail() { Console.WriteLine("My apple laptop can dail now!"); } }
5. 客户端调用:
class Program { static void Main(string[] args) { AppleLaptop laptop = new AppleLaptop(); Handphone hpAdapter = new AppleLatopAdapter(laptop); laptop.Working(); hpAdapter.Dail(); hpAdapter.SendMessage(); Console.ReadLine(); } }
类适配器:
1. 创建接口:Handphone
public interface Handphone { void Dail(); void SendMessage(); }
2. 创建抽象类:Laptop
public abstract class Laptop { public abstract void Working(); }
3. 创建适配器:LaptopAdapter
public class LatopAdapter : Laptop, Handphone { public void SendMessage() { Console.WriteLine("My apple laptop can send message now!"); } public void Dail() { Console.WriteLine("My apple laptop can dail now!"); } public override void Working() { Console.WriteLine("My apple laptop is working now!"); } }
4. 客户端调用:
class Program { static void Main(string[] args) { Handphone ltAdapter = new LatopAdapter(); ltAdapter.Dail(); ltAdapter.SendMessage(); Console.ReadLine(); } }
二、适配器模式设计理念:
适配器模式主要通过添加额外的适配器类,通过对抽象类对扩展接口Handphone中的方法进行实现,同时又保留原类Laptop的方法来实现功能的扩展!
三、角色及关系: