设计模式-适配器模式

适配器模式(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接口。

相关推荐
2302_8057710713 小时前
Day23:POM设计模式(封装)
java·开发语言·设计模式
范中勤2 天前
技术文档:模型工厂 `llm_provider` / `llm_use` 分层设计
设计模式·langchain·架构设计·模型工厂·llm_provider
浅尝辄止;2 天前
设计模式在HIS/LIS医疗系统中的完整实践指南(C#版)
开发语言·设计模式·c#
范中勤2 天前
适配器模式(Adapter Pattern):原理、场景与 LLM 多厂商工程落地
设计模式·架构·langchain·适配器模式·多厂商
408高手2 天前
23种设计模式
设计模式
yuehuaxin012 天前
上海贝岭 BL6523GX(D78) 单相计量芯片开发笔记:引脚定义、寄存器配置与校表流程
嵌入式硬件·智能家居·适配器模式·智能硬件
沫璃染墨2 天前
《Linux工程实践篇(二):线程池实战——从线程安全单例到完整源码实现》
linux·开发语言·c++·单例模式·设计模式·系统架构
sarasuki3 天前
MCP 为什么是一个协议而不是一个框架呢?
设计模式·agent·mcp
geovindu3 天前
rust: Borg Pattern(续)
开发语言·后端·设计模式·rust·博格模式
染指11103 天前
140.Agent-多Agent框架-Agent执行Skills流程
数据库·人工智能·设计模式·langchain·agents