設計模式學習總結(七)適配器模式(Adapter)
阿新 • • 發佈:2017-05-04
實現接口 國外 手機 額外 sed ges program ebe 通過
適配器模式主要是通過適配器來實現接口的統一,如要實現國內手機在國外充電,則需要在不同的國家采用不同的適配器來進行兼容!
一、示例展示:
以下例子主要通過給筆記本電腦添加類似手機打電話和發短信的功能來詳細演示適配器模式的應用!
對象適配器:
1. 創建抽象類:Handphone
public abstract class Handphone { public abstract void Dail(); public abstract void SendMessage(); }View Code
2. 創建抽象類:Laptop
public abstractView Codeclass Laptop { public abstract void Working(); }
3. 創建具體類:AppleLaptop
public class AppleLaptop : Laptop { public override void Working() { Console.WriteLine("Working using laptop!"); } }View Code
4. 創建適配器類:
public class AppleLatopAdapter : Handphone {View Code//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(); } }View Code
類適配器:
1. 創建接口:Handphone
public interface Handphone { void Dail(); void SendMessage(); }View Code
2. 創建抽象類:Laptop
public abstract class Laptop { public abstract void Working(); }View Code
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!"); } }View Code
4. 客戶端調用:
class Program { static void Main(string[] args) { Handphone ltAdapter = new LatopAdapter(); ltAdapter.Dail(); ltAdapter.SendMessage(); Console.ReadLine(); } }View Code
二、適配器模式設計理念:
適配器模式主要通過添加額外的適配器類,通過對抽象類對擴展接口Handphone中的方法進行實現,同時又保留原類Laptop的方法來實現功能的擴展!
三、角色及關系:
設計模式學習總結(七)適配器模式(Adapter)