首页 > 代码库 > 设计模式学习总结(七)适配器模式(Adapter)

设计模式学习总结(七)适配器模式(Adapter)

  适配器模式主要是通过适配器来实现接口的统一,如要实现国内手机在国外充电,则需要在不同的国家采用不同的适配器来进行兼容!

  一、示例展示:

  以下例子主要通过给笔记本电脑添加类似手机打电话和发短信的功能来详细演示适配器模式的应用!

  对象适配器:

   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)