适配器模式(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
相关推荐
代码丰2 天前
项目里接了多个第三方 SDK 后,如何使用适配器模式+策略模式优化?(Adapter + Strategy)
java·适配器模式·策略模式
懵萌长颈鹿2 天前
适配器模式 (Adapter Pattern)
适配器模式
茶本无香3 天前
设计模式之八: 适配器模式解释及应用
java·设计模式·适配器模式
apolloyhl4 天前
Adapter 适配器模式
适配器模式
冷崖4 天前
适配器模式-结构型
适配器模式
进击的小头5 天前
结构型模式:适配器模式(C语言实现与底层实战)
c语言·适配器模式
数据与后端架构提升之路10 天前
TeleTron 源码揭秘:如何用适配器模式“无缝魔改” Megatron-Core?
人工智能·python·适配器模式
会员果汁19 天前
13.设计模式-适配器模式
设计模式·适配器模式
a35354138222 天前
设计模式-适配器模式
设计模式·适配器模式
阿闽ooo1 个月前
深入浅出适配器模式:从跨国插头适配看接口兼容的艺术
c++·设计模式·适配器模式