• 【18】c++设计模式——>适配器模式


    c++的适配器模式是一种结构型设计模式,他允许将一个类的接口转换成另一个客户端所期望的接口。适配器模式常用于已存在的,但不符合新需求或者规范的类的适配。
    在c++中实现适配器模式时,通常需要一下几个组件:
    1.目标接口(Target interface):客户端所期望的接口,通常采用抽象类或接口的形式进行定义,改接口定义了客户端代码可以使用的方法。
    2.适配者(Adaptee):已经存在的,但不符合新需求的类或者接口,其方法不能直接满足客户端代码的需求。
    3.适配器(Adapter):实现了目标接口的类,通过调用适配者的方法来完成客户端所期望的操作。
    下面是一个类适配器的实例代码:

    #include 
    using namespace std;
    
    //目标接口
    class Itarget
    {
    public:
    	virtual void targetMethod() = 0;
    };
    
    //适配者
    class Adaptee
    {
    public:
    	void adapteeMethod()
    	{
    		cout << "我需要被适配" << endl;
    	}
    };
    
    //适配器
    class Adapter :public Itarget,private Adaptee
    {
    public:
    	void  targetMethod()
    	{
    		adapteeMethod();
    	}
    };
    
    int main()
    {
    	Itarget* target = new Adapter;
    	target->targetMethod();
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    在上述示例代码中,ITarget 是目标接口,定义了客户端所期望的方法 targetMethod()。Adaptee 是适配者,包含了一个不符合新需求的方法 adapteeMethod()。Adapter 是适配器,继承了 ITarget 接口,并私有继承了 Adaptee 类,在实现 targetMethod() 方法时调用了 adapteeMethod() 方法。

    在客户端代码中,实例化了一个 Adapter 对象,并将其转换为 ITarget 接口指针。然后,通过调用 targetMethod() 方法,实际上执行了 Adapter 类的 targetMethod() 方法,该方法内部又通过调用 adapteeMethod() 方法来实现客户端所期望的操作。

    总结来说,适配器模式是一种将不符合客户端需求的类或接口转换成符合需求的类或接口的设计模式。在C++中,可以通过类适配器或对象适配器的方式来实现适配器模式。

  • 相关阅读:
    ORB-SLAM2算法15之回环检测线程Loop Closing
    教你用HTML+CSS实现百叶窗动画效果
    Flex布局的三个属性要深刻理解!
    Linux CPU之mpstat
    【C++】-- 红黑树详解
    解耦、异步、削峰是什么
    数据权限就该这么设计,yyyds!
    Spark系列之Spark启动与基础使用
    记录一个iOS使用陀螺仪3d效果的抖动问题
    多数据源切换
  • 原文地址:https://blog.csdn.net/weixin_42097108/article/details/133625180