设计模式-适配器模式

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

相关推荐
Zane19942 小时前
从一次支付渠道扩展需求,看懂"多用组合少用继承"到底在说什么
设计模式
geovindu3 小时前
CSharp:Condition Variable Pattern
后端·设计模式·c#·.net·.netcore·条件变量模式·同步型模式
geovindu3 小时前
sql: Data Modeling Patterns using mysql
sql·mysql·设计模式·数据库开发
sarasuki1 天前
失败重试:Agent 中指数退避的正确姿势
人工智能·设计模式·agent
Zane19941 天前
为什么你写的 Java 代码"看着面向对象、实际是面向过程"?
设计模式
geovindu1 天前
sql: Data Modeling Patterns
数据库·sql·设计模式·sqlserver
YHL3 天前
🎯 JavaScript 单例模式(Singleton Pattern)—— 从理论到实战
javascript·设计模式
2401_868534783 天前
网络环境规划核心考点全梳理
网络·设计模式
feiyu_gao3 天前
Cocreation Framework:一套给所有人的 AI 协作思考系统
设计模式·aigc·ai编程
善良勤劳勇敢而又聪明的老杨4 天前
【AI编程系列】MCP 常用设计模式解读
设计模式·ai编程