C++实现设计模式:Bridge Pattern

来源:互联网 发布:中国软件行业协会aaa 编辑:程序博客网 时间:2024/05/16 18:04

注:为了简要说明,类的成员函数均采用inline。

#ifndef _DRIVE_GAME_H_
#define _DRIVE_GAME_H_

#include "DriveGameImpl.h"

#include <iostream>
using std::cout;
using std::endl;

class DriveGame
{
public:
    DriveGame(DriveGameImpl* impl):_impl(impl){}

    virtual ~DriveGame(){}
    virtual void init()
    {
        cout<<"Init the game."<<endl;
        _impl->display();
        _impl->flush();
    }
    virtual void startGame() = 0
    {
        //Omit for brief description.
    }
    
private:
    DriveGameImpl* _impl;
};

class DriveGame_3D:public DriveGame
{
public:
    DriveGame_3D(DriveGameImpl* impl):DriveGame(impl)
    {
        //Omit for brief description.
    }

    ~DriveGame_3D()
    {
        //To clear the status of the game.
    }

    virtual void startGame()
    {
        init();
        cout<<"Start 3D Drive Game."<<endl;
    }

private:
    //Omit for brief description.
};

class DriveGame_2D:public DriveGame
{
public:
    DriveGame_2D(DriveGameImpl* impl):DriveGame(impl)
    {
        //
    }

    ~DriveGame_2D()
    {
        //To clear the status of the game.
    }
    virtual void startGame()
    {
        init();
        cout<<"Start 2D Drive Game."<<endl;
    }

private:
    //Omit for brief description.
};

#endif



#ifndef _DRIVE_GAME_IMPL_H_
#define _DRIVE_GAME_IMPL_H_

#include <iostream>
using std::cout;
using std::endl;
using std::string;

class DriveGameImpl
{
public:
    virtual ~DriveGameImpl(){}
    virtual void display()=0{}
    virtual void flush()=0{}
    
};

class LinuxDriveGameImpl:public DriveGameImpl
{
public:
    ~LinuxDriveGameImpl(){}
    void display()
    {
        cout<<"Linux system: display the game."<<endl;
    }
    void flush()
    {
        cout<<"Linux system: flush the game."<<endl;
    }
};

class WindowsDriveGameImpl:public DriveGameImpl
{
public:
    ~WindowsDriveGameImpl(){}
    void display()
    {
        cout<<"windows system: display the game."<<endl;
    }
    void flush()
    {
        cout<<"windows system: flush the game."<<endl;
    }
};

#endif


#include <iostream>

#include "DriveGame.h"
#include "DriveGameImpl.h"

using std::cout;
using std::endl;
using std::string;

int main()
{
    DriveGameImpl* linuxGameImpl = new LinuxDriveGameImpl();
    DriveGame* game_2D_Linux = new DriveGame_2D(linuxGameImpl);
    game_2D_Linux->startGame();
    
    system("PAUSE");
}




原创粉丝点击