Skip to content

适配器(Adapter)模式 结构型模式

将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。

c#
// 适配器模式示例
using System;

// 定义一个目标接口,即客户端所期望的接口
interface ITarget
{
    void Request();
}

// 定义一个适配者类,即需要被适配的类
class Adaptee
{
    public void SpecificRequest()
    {
        Console.WriteLine("适配者类的特殊请求");
    }
}

// 定义一个适配器类,实现目标接口,同时持有一个适配者类的实例
class Adapter : ITarget
{
    private Adaptee adaptee = new Adaptee();

    public void Request()
    {
        adaptee.SpecificRequest();
    }
}

class Program
{
    static void Main(string[] args)
    {
        // 创建一个适配器对象
        ITarget target = new Adapter();
        // 调用目标接口的方法,实际上是调用适配者类的方法
        target.Request();

        Console.ReadKey();
    }
}
你觉得这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度