初学设计模式之适配器模式
代码例子
1 //适配器模式 2 #include<iostream> 3 #include<string> 4 using namespace std; 5 class AbstractTarget 6 { 7 public: 8 string getName(){}; 9 string getPhoneNum(){}; 10 string getHomeAdr(){}; 11 string getJob(){}; 12 string getOfficeNum(){}; 13 }; 14 class ConcreteTarget 15 { 16 public: 17 string getName() 18 { 19 cout<<"名字"<<endl; 20 return "名字"; 21 }; 22 string getPhoneNum() 23 { 24 cout<<"电话号码"<<endl; 25 return "电话号码"; 26 }; 27 string getHomeAdr() 28 { 29 cout<<"家庭地址"<<endl; 30 return "家庭地址"; 31 }; 32 string getJob() 33 { 34 cout<<"工作职位"<<endl; 35 return "工作职位"; 36 }; 37 string getOfficeNum() 38 { 39 cout<<"办公室电话"<<endl; 40 return "办公室电话"; 41 }; 42 }; 43 struct INFOR 44 { 45 string name; 46 string phoneNum; 47 string homeAdr; 48 string job; 49 string officeNum; 50 }; 51 class AbstractOrigin 52 { 53 public: 54 INFOR getInfor() 55 { 56 57 } 58 }; 59 60 class ConcreteOrigin:public AbstractOrigin 61 { 62 protected: 63 INFOR m_info; 64 public: 65 INFOR getInfor() 66 { 67 INFOR m_infor={"name","Num","HomeAdr","Job","Office"}; 68 return m_infor; 69 } 70 }; 71 72 class Adapter:public ConcreteOrigin 73 { 74 public: 75 string getName() 76 { 77 INFOR m_infor=getInfor(); 78 cout<<m_infor.name<<endl; 79 return m_infor.name; 80 }; 81 string getPhoneNum() 82 { 83 cout<<getInfor().phoneNum<<endl; 84 return getInfor().phoneNum; 85 }; 86 string getHomeAdr() 87 { 88 cout<<getInfor().homeAdr<<endl; 89 return getInfor().homeAdr; 90 }; 91 string getJob() 92 { 93 cout<<getInfor().job<<endl; 94 return getInfor().job; 95 }; 96 string getOfficeNum() 97 { 98 cout<<getInfor().officeNum<<endl; 99 return getInfor().officeNum; 100 }; 101 }; 102 103 int main() 104 { 105 ConcreteTarget m_ConcreteTarget; 106 cout<<m_ConcreteTarget.getName()<<endl;; 107 Adapter m_Adapter; 108 cout<<m_Adapter.getName()<<endl; 109 110 getchar(); 111 return 0; 112 };