设计模式-适配器模式

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

相关推荐
cpp_learner32 分钟前
C++ 实现责任链模式(Chain of Responsibility):从一堆 if-else 到可插拔的处理管道
c++·设计模式
码匠许师傅1 小时前
【设计模式精讲】23.备忘录模式(Memento)
c++·设计模式·软件工程·uml·备忘录模式
新知图书17 小时前
第8章 多智能体协同
人工智能·设计模式·智能体
京师20万禁军教头21 小时前
39面向对象(高级)-设计模式
java·开发语言·设计模式
新知图书1 天前
3.5 智能体设计模式1:反应式智能体与自动导航案例
人工智能·设计模式·智能体
码匠许师傅1 天前
【设计模式精讲】21.迭代器模式(Iterator)
c++·设计模式·rpc·迭代器模式·软件工程·uml
Carl_奕然2 天前
【智能体】Agent的四种设计模式之:React(2026最新版)
javascript·人工智能·python·react.js·设计模式·语言模型
cfm_29142 天前
Spring核心设计模式
java·spring·设计模式
码匠许师傅3 天前
【设计模式精讲】15.享元模式(Flyweight)
c++·设计模式·享元模式·uml
事圆则缓3 天前
Android 常用设计模式速查
android·设计模式