现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

Adapter模式C++实现

2012-08-21 05:53 工业·编程 ⁄ 共 1812字 ⁄ 字号 暂无评论

说明:《Head First设计模式》第七章Adapter模式C++实现,用火鸡来模仿鸭子。

鸭子类Duck.h:

#pragma once
#include <iostream>
using namespace std;

//鸭子
class IDuck
{
public:
    virtual ~IDuck(){}

    //呱呱叫
    virtual void Quack() = 0;
    //飞行
    virtual void Fly() = 0;
};

//绿头鸭
class CMallardDuck : public IDuck
{
public:
    void Quack()
    {
        cout<<"Quack"<<endl;
    }

    void Fly()
    {
        cout<<"I'm flying"<<endl;
    }
};

火鸡类Turkey.h:

#pragma once
#include <iostream>
using namespace std;

//火鸡
class ITurkey
{
public:
    virtual ~ITurkey(){}

    //咕咕叫
    virtual void Gobble() = 0;
    //飞行
    virtual void Fly() = 0;
};

class CWildTurkey : public ITurkey
{
public:
    void Gobble()
    {
        cout<<"Gobble gobble"<<endl;
    }

    void Fly()
    {
        cout<<"I'm flying a short distance"<<endl;
    }
};

适配器类TurkeyAdapter.h:

#pragma once
#include "Duck.h"
#include "Turkey.h"

//用火鸡模仿鸭子
class CTurkeyAdapter : public IDuck
{
public:
    CTurkeyAdapter(ITurkey* pTurkey)
        : m_pTurkey(pTurkey)
    {

    }

    void Quack()
    {
        m_pTurkey->Gobble();
    }

    void Fly()
    {
        //火鸡飞行距离短,飞行五次模拟鸭子
        for (int i = 0; i < 5; i++)
        {
            m_pTurkey->Fly();
        }
    }

private:
    ITurkey* m_pTurkey;
};

调用方法:

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;

// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
  // TODO: change error code to suit your needs
  _tprintf(_T("Fatal Error: MFC initialization failed\n"));
  return 1;
}

    //创建鸭子
    IDuck* pDuck = new CMallardDuck();
    //创建火鸡
    ITurkey* pTurkey = new CWildTurkey();
    //创建火鸡适配器
    IDuck* pAdapter = new CTurkeyAdapter(pTurkey);

    cout<<"The Turkey says..."<<endl;
    pTurkey->Gobble();
    pTurkey->Fly();

    cout<<"\nThe Duck says..."<<endl;
    pDuck->Quack();
    pDuck->Fly();

    cout<<"\nThe TurkeyAdapter says..."<<endl;
    pAdapter->Quack();
    pAdapter->Fly();

    delete pAdapter;
    pAdapter = NULL;
    delete pTurkey;
    pTurkey = NULL;
    delete pDuck;
    pDuck = NULL;

return nRetCode;
}

给我留言

留言无头像?