设计模式-适配器模式

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

相关推荐
小程故事多_804 小时前
从Claude Code源码中,拆解13个可直接复用的Agentic Harness设计模式(生产级实战解析)
人工智能·设计模式·智能体·claude code·harness
踩着两条虫9 小时前
VTJ 平台六大设计模式落地实战指南
开发语言·前端·人工智能·低代码·设计模式·重构·架构
石油人单挑所有11 小时前
基于多设计模式下的同步&异步日志系统测试报告
服务器·c++·vscode·设计模式
geovindu14 小时前
go:Decorator Pattern
开发语言·设计模式·golang·装饰器模式
ximu_polaris14 小时前
设计模式(C++)-行为型模式-观察者模式
c++·观察者模式·设计模式
Lands1 天前
推荐一下配合agent开发的工具
设计模式·agent
不才小强1 天前
行为型设计模式
设计模式
ximu_polaris1 天前
设计模式(C++)-结构型模式-享元模式
c++·设计模式·享元模式
geovindu1 天前
go: Facade Pattern
设计模式·golang·外观模式
旷世奇才李先生2 天前
React 18\+TypeScript实战: hooks封装与组件设计模式
react.js·设计模式·typescript