结构型模式
10)代理模式
本文参考
代理模式贯彻了面对对象程序的开闭原则(对修改关闭,对扩展开放),在不改变原本类的情况下,修改用户的使用接口。
也就是为其他类提供一种代理,以控制对这个类的访问。真正调用时只让代理出现,不让真正的用户出现。
一般来说包括两个角色:
第一种,对象类。
第二种,代理类。
需要注意的是上面两个角色需要继承自同一基类。
例如在游戏中,通过代理来控制不同用户的访问权限。
//基本游戏接口 class play{ public: virtual void play1() = 0; virtual void play2() = 0; }; //玩家接口 class player : public play{ public: void play1(){ cout<<"装备1"<<endl; } void play2(){ cout<<"装备2"<<endl; } void play3(){ cout<<"装备3"<<endl; } }; //代理玩家1 class proxyPlayer1 : public play{ public: proxyPlayer1(){ m_player = new player(); } void play1(){ m_player->play1(); } void play2(){ cout<<"没有权限"<<endl; } private: player* m_player; }; //代理玩家2 class proxyPlayer2 : public play{ public: proxyPlayer2(){ m_player = new player(); } void play1(){ m_player->play1(); } void play2(){ m_player->play2(); } private: player* m_player; }; int main(){ proxyPlayer1* p1 = new proxyPlayer1(); p1->play1(); p1->play2(); cout<<"==="<<endl; proxyPlayer2* p2 = new proxyPlayer2(); p2->play1(); p2->play2(); }
最后输出为
来源:https://www.cnblogs.com/corineru/p/12019601.html