设计模式-适配器模式

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

相关推荐
繁华似锦respect1 小时前
lambda表达式中的循环引用问题详解
java·开发语言·c++·单例模式·设计模式·哈希算法·散列表
星月IWJ4 小时前
领域驱动设计学习
java·学习·设计模式
_dindong5 小时前
Linux网络编程:Reactor反应堆模式
linux·服务器·网络·设计模式·php
雨中飘荡的记忆5 小时前
Step Builder模式实战
java·设计模式
Eren7Y琳6 小时前
开箱即用构建应用环境:openEuler易获得性深度验证
redis·设计模式·架构
Unstoppable226 小时前
八股训练营第 39 天 | Bean 的作用域?Bean 的生命周期?Spring 循环依赖是怎么解决的?Spring 中用到了那些设计模式?
java·spring·设计模式
闲人编程7 小时前
微服务API网关设计模式
python·缓存·微服务·设计模式·系统安全·api·codecapsule
__万波__7 小时前
二十三种设计模式(八)--装饰器模式
java·设计模式·装饰器模式
@小白鸽7 小时前
1.2.2结构型设计模式
设计模式
繁华似锦respect18 小时前
C++ 智能指针底层实现深度解析
linux·开发语言·c++·设计模式·代理模式