设计模式 BY C++C++设计模式

【C++ 设计模式】6.适配器模式

2019-10-20  本文已影响0人  JeremyYv

以下是类适配器模式的简单代码实现
#include <iostream>
using namespace std;
//市电类
class Electricity
{
public:
    virtual void Charge()//使用市电进行充电,输出验证电压的数值
    {
        cout << "220V charging..." << endl;
    }
};

//适配器类
class Adapter5V
{
public:
    void Transfer()//将电压转换为5V,输出验证
    {
        cout << "5V charging..." << endl;
    }
};

//类适配器,使用多继承的方式
class ElecWithAdapter5V:public Electricity, Adapter5V
{
public:
    virtual void Charge()//重写充电方法
    {
        Transfer();//直接调用适配器电压转换方法
    }
};
主函数中的使用
#include <iostream>
#include "ClassAdapter.h"
using namespace std;
int main()
{
    Electricity* pEle = new Electricity();//如果不使用适配器
    pEle->Charge();

    Electricity* pEleWithAdapter = new ElecWithAdapter5V();//使用适配器
    pEleWithAdapter->Charge();

    return 0;
}
控制台输出结果
220V charging...
5V charging...

以下是对象适配器模式的简单代码实现
#include <iostream>
using namespace std;
//市电类
class Electricity
{
public:
    virtual void Charge()//使用市电进行充电,输出验证电压的数值
    {
        cout << "220V charging..." << endl;
    }
};

//适配器类
class Adapter5V
{
public:
    void Transfer()//将电压转换为5V,输出验证
    {
        cout << "5V charging..." << endl;
    }
};

//对象适配器
class ElecWithAdapter5V:public Electricity
{
public:
    ElecWithAdapter5V():pAdapter(NULL)
    {
        pAdapter = new Adapter5V();
    }
    virtual void Charge()//重写充电方法
    {
        pAdapter->Transfer();//通过适配器指针,调用电压转换方法
    }

private:
    Adapter5V* pAdapter;
};
主函数中的使用
#include <iostream>
#include "ObjectAdapter.h"
using namespace std;
int main()
{
    Electricity* pEle = new Electricity();//如果不使用适配器
    pEle->Charge();

    Electricity* pEleWithAdapter = new ElecWithAdapter5V();//使用适配器
    pEleWithAdapter->Charge();

    return 0;
}
控制台输出结果
220V charging...
5V charging...

如有错误,欢迎指正

上一篇 下一篇

猜你喜欢

热点阅读