Adapter设计模式

#include <iostream>
#define CCLASS
class Target
{
public:
	virtual void Request(){};
};
class Adaptee
{
public:
	void SpecificRequest()
	{
		std::cout<<"SpecificRequest"<<std::endl;
	};
};
 #ifdef CCLASS  // calss pattern 
   class Adapter: public Target, private Adaptee
{
public:
void Request()
	{
		SpecificRequest();
}
};

#else 
class Adapter:public Target //Object pattern 
{
public:
Adapter(Adaptee* ade);
~Adapter();
virtual void Request();
private:
Adaptee* _ade;
};
Adapter::Adapter(Adaptee* ade)
{
this->_ade=ade;
}
void Adapter::Request()
{
_ade->SpecificRequest();
}
#endif
int main(int argc, char* argv[])
{
#ifdef CCLASS
	Target* p=new Adapter();
	p->Request();
#else
Adaptee* ade=new Adaptee;
Target* adt=new Adapter(ade);
adt->Request();
#endif
return 0;
}

分为类模式和对象模式

类模式主要是Adapter同时继承Target和Adaptee

然后用函数把Adapter的需求转换为Adaptee


对象模式主要是Adapter继承Target, 然后包含Adaptee

通过Adapter的私有Adaptee× 指向包含进来的Adaptee×,

通过函数, Adapter的需求为私有Adaptee*的需求,私有Adaptee*的需求指向包含进来的私有Adaptee*的需求



你可能感兴趣的:(设计模式,C++,Adapter)