适配器模式Adapter

    xiaoxiao2022-06-28  34

    适配器模式是结构性模式的一种,目的是将第三方提供的不兼容接口适配成我们的目标接口。

    采用public继承ITarget类,此为接口继承;采用private继承CThridParty类,此为实现继承。

    下面的演示代码采用的是组合的方法。遵循组合优于继承的原则。

    #ifndef __ADAPTER_H__ #define __ADAPTER_H__ class CThirdParty { public: CThirdParty() {} ~CThirdParty() {} public: void Realize() {printf("CThirdParty::Realize()\n");} }; class ITarget { protected: ITarget() {} virtual ~ITarget() {} public: virtual void Request() = 0; }; class CTarget : public ITarget { public: CTarget() {} ~CTarget() {} void Request() {m_cThrid.Realize();} private: CThirdParty m_cThrid; }; #endif // __ADAPTER_H__#include "stdafx.h" #include "Adapter.h" int _tmain(int argc, _TCHAR* argv[]) { ITarget* pTarget = new CTarget; pTarget->Request(); getchar(); return 0; }

    ithewei 认证博客专家 c/c Qt libhv 编程之路,其路漫漫,吾将上下而求索https://github.com/itheweihttps://hewei.blog.csdn.net
    转载请注明原文地址: https://ju.6miu.com/read-1124636.html

    最新回复(0)