设计模式-适配器模式

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

相关推荐
workflower18 小时前
AI能源智慧生产与绿色开发核心场景
大数据·人工智能·设计模式·机器人·软件工程·能源
蜡笔小马18 小时前
10.C++设计模式-代理模式
c++·设计模式·代理模式
雪度娃娃19 小时前
行为型设计模式——职责链模式
c++·设计模式·责任链模式
多加点辣也没关系1 天前
设计模式-观察者模式
观察者模式·设计模式
hssfscv1 天前
软件设计师下午题训练1-3题+2019上上午题错题解析 练习真题训练13
笔记·设计模式·uml
拾-光1 天前
【Git】命令大全:从入门到高手,100 个最常用命令速查(2026 版)
java·大数据·人工智能·git·python·elasticsearch·设计模式
多加点辣也没关系1 天前
设计模式-模板方法模式
设计模式·模板方法模式
Autumn_ing2 天前
2026实测:这5款AI生成UI工具支持Shadcn UI/Ant Design组件库
人工智能·ui·设计模式·aigc·设计规范
woniu_buhui_fei2 天前
常用设计模式
设计模式·架构
likerhood2 天前
设计模式 · 组合模式(Composite Pattern)
设计模式·组合模式