设计模式之类对象结构型 — ADAPTER (适配器)模式

来源:互联网 发布:如何应对压力 知乎 编辑:程序博客网 时间:2024/05/24 03:38

概述

适配器模式可以将一个类的接口转换成客户希望的另一个类的接口

效果

类适配器

  • 一个具体的Adapter(适配器)类对Adaptee(被适配者)和Target(目标)进行匹配
  • Adapter可以重定义Adaptee的部分行为
  • 不需要额外的指针以间接得到adaptee

对象适配器

  • 允许Adapter与Adaptee及其子类一起工作。
  • 重定义Adaptee的行为比较困难,需要生成他的子类才可以重定义

结构

这里写图片描述

示例代码

class Adaptee{public:    Adaptee();    ~Adaptee();    void func_a();    void func_b();protected:private:};class Target{public:    Target();    virtual ~Target();    virtual bool func_c(int a);protected:private:};/************************************************************************//* 类适配器*//************************************************************************/class Adapter :public Target ,private Adaptee {public:    Adapter();    ~Adapter();    bool func_c(int a)    {        func_a();        func_b();        return true;    }protected:private:};/************************************************************************//* 对象适配器                                                                     *//************************************************************************/class Adapter :public Target{public:    Adapter(Adaptee *adaptee)    {        m_adaptee = adaptee;    }    ~Adapter();    bool func_c(int a)    {        m_adaptee->func_a();        m_adaptee->func_b();        return true;    }protected:private:    Adaptee *m_adaptee;};

我的个人网站 http://www.breeziness.cn/
我的CSDN http://blog.csdn.net/qq_33775402

转载请注明出处 小风code www.breeziness.cn

阅读全文
0 0
原创粉丝点击