Template模式、类适配器、对象适配器的C++实现
1、Template:
C++实现代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <bits/stdc++.h> using namespace std; class AbstractClass { public: void TemplateMethod() { cout<<"PrimitiveOper1() Start"<<endl; PrimitiveOper1(); cout<<"PrimitiveOper1() End"<<endl; cout<<"PrimitiveOper2() Start"<<endl; PrimitiveOper2(); cout<<"PrimitiveOper2() End"<<endl; } protected: virtual void PrimitiveOper1() { cout<<"AbstractClass oper1"<<endl; } virtual void PrimitiveOper2() { cout<<"AbstractClass oper2"<<endl; } }; class ConcreteClass:public AbstractClass { protected: virtual void PrimitiveOper1() { cout<<"ConcreteClass Oper1"<<endl; } virtual void PrimitiveOper2() { cout<<"ConcreteClass Oper2"<<endl; } }; int main() { AbstractClass * pa=new ConcreteClass(); pa->TemplateMethod(); if(pa) delete pa; return 0; }
2、类适配器
C++实现代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <bits/stdc++.h> using namespace std; class Target { public: virtual void Request() { cout<<"Target::Request"<<endl; } }; class Adaptee { public: void SpecificRequest() { cout<<"Adaptee::SpecificRequest"<<endl; } }; class Adapter:public Target,Adaptee { public: void Request() { Adaptee::SpecificRequest(); } }; int main() { Target *pt=new Adapter(); pt->Request(); if(pt) delete pt; return 0; }
3、对象适配器
C++实现代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <bits/stdc++.h> using namespace std; class Target { public: Target(){} virtual void Request() { cout<<"Target::Request"<<endl; } }; class Adaptee { public: void SpecificRequest() { cout<<"Adaptee::SpecificRequest"<<endl; } }; class Adapter:public Target,Adaptee { public: Adapter():m_adaptee(new Adaptee){} ~Adapter() { if(m_adaptee!=NULL) { delete m_adaptee; } } void Request() { m_adaptee->SpecificRequest(); } private: Adaptee *m_adaptee; }; int main() { Target *pt=new Adapter(); pt->Request(); if(pt) delete pt; return 0; }