适配器模式(AdapterPattern)

文章目录

1.适配器模式定义

使接口不兼容的对象能够相互合作

2.UML类图

  • 目标角色(Target):定义Client使用的与特定领域相关的接口。
  • 客户角色(Client):与符合Target接口的对象协同。
  • 被适配角色(Adaptee):定义一个已经存在并已经使用的接口,这个接口需要适配。
  • 适配器角色(Adapte) :适配器模式的核心。它将对被适配Adaptee角色已有的接口转换为目标角色Target匹配的接口。对Adaptee的接口与Target接口进行适配.

3.实现代码

接口对象:

csharp 复制代码
public interface IAdaptee
{
    public void AdapteeMethod();
}

public interface ITarget
{
    public void TargetMehtod();
}

public class Target : ITarget
{
    public void TargetMehtod()
    {
        Console.WriteLine("Target call TargetMehtod");
    }
}

适配器类:

csharp 复制代码
public class Adapte : IAdaptee
{
    public Target _target;

    public Adapte(Target target)
    {
        _target = target;
    }

    public void AdapteeMethod()
    {
        _target.TargetMehtod();
    }
}

测试类:

csharp 复制代码
Adapte adapte = new Adapte(new Target());
adapte.AdapteeMethod();

// Target call TargetMehtod
相关推荐
折哥的程序人生 · 物流技术专研13 天前
Java 23 种设计模式:从踩坑到精通 | 适配器模式 —— 让不兼容的接口也能一起工作
java·设计模式·面试·适配器模式·单一职责原则
basketball61622 天前
设计模式入门:3. 适配器模式详解 C++实现
c++·设计模式·适配器模式
晚风吹红霞22 天前
C++ stack 和 queue 完全指南:适配器模式与双端队列的奥秘
c++·算法·适配器模式
Rick199323 天前
代理模式 vs 适配器模式
代理模式·适配器模式
老码观察1 个月前
设计模式实战解读(七):适配器模式——让不兼容的接口无缝协作
java·设计模式·适配器模式
nnsix1 个月前
设计模式 - 适配器模式 笔记
笔记·设计模式·适配器模式
雪碧聊技术1 个月前
什么是适配器模式?一文详解
适配器模式
蜡笔小马1 个月前
05.C++设计模式-适配器模式
c++·设计模式·适配器模式
c++之路1 个月前
适配器模式(Adapter Pattern)
java·算法·适配器模式
Forget the Dream1 个月前
基于适配器模式的 Axios 封装实践
设计模式·typescript·axios·适配器模式