定义:为其他对象提供一种代理以控制这个对象的访问,也叫做委托模式。
咱们比作游戏,通俗讲代理模式就是,一个主题虚基类派生出两个子类,一个玩家类,实现相关操作,一个是代练类,代替执行玩家相关操作,代练类对象有个指向玩家类对象的指针,可以通过调用代练类对象,实现玩家不登录,游戏照样打怪升级。。。。
using namespace std; //游戏主题类 class Game { public:Game() {}virtual ~Game() {}virtual void begin_time() = 0;virtual void login() = 0;virtual void killBoss() = 0;virtual void upGrade() = 0;virtual void end_time() = 0; };//游戏实例 class RealGame : public Game { public:RealGame(string username, string password) {this->userName = username;this->password = password;}~RealGame() {}//上线virtual void begin_time() { printf("开始时间: 2017/3/20 19:34 "); }//登录virtual void login() { cout <<"用户: " <"登录游戏"<< endl;}//打怪virtual void killBoss() { cout << userName << "打死领主"锤王菠萝丁!"" << endl;}//升级virtual void upGrade() { cout << userName << "升级到89级!" << endl;}//下线virtual void end_time() {cout <<"2017/3/20 21:12 玩家"<< userName << "退出游戏" << endl;}private:string userName;string password; };//游戏代练者 class Proxy : public Game { public:Proxy(string userName, string password){pRealGame = new RealGame(userName, password);}~Proxy() {delete pRealGame;pRealGame = nullptr;}virtual void begin_time() {pRealGame->begin_time();}virtual void login(){pRealGame->login();}virtual void killBoss(){pRealGame->killBoss();}virtual void upGrade(){pRealGame->upGrade();}virtual void end_time(){pRealGame->end_time();}private:RealGame *pRealGame; };int main() {Game *m_game = new Proxy("张三","******");m_game->begin_time();m_game->login();m_game->killBoss();m_game->upGrade();m_game->end_time();delete m_game;m_game = nullptr; }