设计模式之代理模式

 1 #include<iostream>
 2 using namespace std;
 3 #include<string>
 4 
 5 //代理模式:为其他对象提供一种代理以控制对这个对象的访问
 6 
 7 class abstractCommonInterface{
 8 public:
 9     virtual void run()=0;
10 };
11 
12 class mySystem:public abstractCommonInterface{
13 public:
14     virtual void run(){
15         cout<<"system start"<<endl;
16     }
17 };
18 
19 //系统必须要权限的验证,不是每个人都能来启动,需要用户名和密码
20 //代理类
21 class mySystemProxy:public abstractCommonInterface{
22 public:
23     mySystemProxy(string name,string password):mName(name),mPassword(password){    
24         pMysystem=new mySystem;
25     }
26     bool checkAuthority(){
27         if(mName=="admin"&&mPassword=="admin"){
28             return true;
29         }
30         return false;
31     }
32     virtual void run(){
33         if(checkAuthority()){
34             this->pMysystem->run();
35             cout<<"checkAuthority correct"<<endl;
36         }else{
37             cout<<"name or password error"<<endl;
38         }
39     }
40     ~mySystemProxy(){
41         if(pMysystem!=NULL){
42             delete pMysystem;
43         }
44     }
45     mySystem* pMysystem;
46     string mName;
47     string mPassword;
48 };
49 int main()
50 {
51     mySystemProxy* system=new mySystemProxy("admin","admin");
52     system->run();
53     return 0;
54 }

 

posted @ 2020-04-07 16:23  njit-sam  阅读(86)  评论(0编辑  收藏  举报