1. 程式人生 > >設計模式學習總結(七)適配器模式(Adapter)

設計模式學習總結(七)適配器模式(Adapter)

實現接口 國外 手機 額外 sed ges program ebe 通過

  適配器模式主要是通過適配器來實現接口的統一,如要實現國內手機在國外充電,則需要在不同的國家采用不同的適配器來進行兼容!

  一、示例展示:

  以下例子主要通過給筆記本電腦添加類似手機打電話和發短信的功能來詳細演示適配器模式的應用!

  對象適配器:

  1. 創建抽象類:Handphone

技術分享
public abstract class Handphone
{
    public abstract void Dail();
    public abstract void SendMessage();
}
View Code

  2. 創建抽象類:Laptop

技術分享
public abstract
class Laptop { public abstract void Working(); }
View Code

  3. 創建具體類:AppleLaptop

技術分享
public class AppleLaptop : Laptop
{
    public override void Working()
    {
        Console.WriteLine("Working using laptop!");
    }
}
View Code

  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!"); } }
View Code

  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)