设计模式-适配器模式

适配器模式(Adapter Pattern)是一种软件设计模式,它能使接口不兼容的两个类可以协同工作。该模式的核心是转换接口,将一个类的接口转换成客户端期望的另一个接口。在C#中,适配器模式可以通过继承或者组合的方式实现。

以下是一个使用组合实现的适配器模式的示例代码:

cs 复制代码
// 目标接口(客户期望的接口)
public interface ITarget
{
    void SpecificRequest();
}
 
// 需要适配的类
public class Adaptee
{
    public void SpecificMethod()
    {
        // 实现一些功能
    }
}
 
// 适配器类
public class Adapter : ITarget
{
    private Adaptee _adaptee;
 
    public Adapter(Adaptee adaptee)
    {
        _adaptee = adaptee;
    }
 
    public void SpecificRequest()
    {
        // 在适配器类内部调用需要适配的类的方法
        _adaptee.SpecificMethod();
    }
}
 
// 客户端代码
public class Client
{
    public void MainFunction()
    {
        Adaptee adaptee = new Adaptee();
        ITarget target = new Adapter(adaptee);
        
        // 客户端只知道ITarget接口
        target.SpecificRequest();
    }
}

在这个例子中,ITarget是客户期望的接口,Adapter是适配器,它将Adaptee的接口转换成了ITarget的接口,这样客户端就可以通过ITarget接口来调用Adaptee的功能。这里使用了组合的方式,Adapter类包含了一个Adaptee类型的实例,并且实现了ITarget接口。

相关推荐
沫璃染墨6 小时前
《Linux工程实践篇(一):认识设计模式——从日志系统看策略模式》
linux·c++·安全·设计模式·策略模式
十六宿舍8 小时前
【软件设计模式-第一课:基础知识了解】
设计模式·架构·面向对象·软件架构
geovindu11 小时前
rust: Facade Pattern
开发语言·后端·设计模式·rust·外观模式
怕浪猫13 小时前
面试官让我手写一个 Tool Use,我用了 3 种方案
设计模式·面试·程序员
geovindu1 天前
rust: Abstract Factory pattern
开发语言·后端·设计模式·rust·抽象工厂模式
yuehuaxin011 天前
LP20R100FN 同步整流|3C 认证适配器 CCM 工况倒灌、温升超标样机避坑解析
嵌入式硬件·智能家居·适配器模式·智能硬件
yuehuaxin012 天前
LP3710S 原边 PSR|3C 认证适配器 Peak‑Load 瞬时冲击、EMI 传导骚扰样机避坑解析
嵌入式硬件·适配器模式·智能硬件
Carl_奕然2 天前
【智能体】Loop 的四种设计模式之:Event-Driven Loop(2026 最新版)
人工智能·驱动开发·python·设计模式
Carl_奕然2 天前
【智能体】Loop 的四种设计模式之:Hill Climbing Loop(2026 最新版)
人工智能·python·设计模式
晚安code2 天前
设计模式入门:吃透 SOLID 原则与迪米特法则,再学 5 个高频模式
后端·设计模式