using namespace std;
using namespace boost;
/**
* @brief 将一个类的接口转换成客户希望的另外一个接口,解决两个已有接口之间不匹配的问题。
Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
@Note Adapter可以有两种实现方法,分别为类和对象的版本。
Adapter和Adaptee之间是is-a关系的时候,属于类适配器,Adapter和Adaptee之间是has-a关系的时候,属于对象适配器。
“当涉及到依存性时,应当始终优先选择组合/成员关系而不是继承”的设计原则(<Exceptional C++>)
,并且由于多继承在使用上的复杂性,及在部分情况下不可行等原因,Object Adapter的运用显得更加广泛。
对象版本实现也更为复杂,但灵活性更强。传入一个Adaptee子类的指针,可以使Adapter与其子类很好的一起工作。
*/
// 以下为类实现方式
/** @brief 原始的功能类 */
class Adaptee
{
public:
Adaptee(void)
{
cout << "Adaptee Construction" << endl;
}
void SpecialRequest()
{
cout << "SpecialRequest" << endl;
}
};
/** @brief 需要匹配的接口 */
class Target
{
public:
Target(void)
{
cout << "Target Construction" << endl;
}
virtual ~Target(void)
{
cout << "Target Destruction" << endl;
}
virtual void Request() = 0;
};
/** @brief class Adapter */
/**
class Adapter : public Target , private Adaptee
{
public:
Adapter(void)
{
cout << "class Adapter Construction" << endl;
}
virtual void Request()
{
SpecialRequest();
}
};
*/
/** @brief object Adapter */
class Adapter : public Target
{
public:
Adapter(Adaptee* pAdaptee) : m_pAdaptee(pAdaptee)
{
cout << "object Adapter Construction" << endl;
}
virtual ~Adapter(void)
{
cout << "object Adapter Destruction" << endl;
if(m_pAdaptee != NULL)
{
delete m_pAdaptee;
m_pAdaptee = NULL;
}
}
virtual void Request()
{
m_pAdaptee->SpecialRequest();
}
private:
Adaptee* m_pAdaptee;
};
int _tmain(int argc, _TCHAR* argv[])
{
/** @brief class Adapter方式调用 */
/**
scoped_ptr<Target> pTarget(new Adapter());
pTarget->Request();
*/
/** @brief Object Adapter方式调用 */
scoped_ptr<Target> pTarget(new Adapter(new Adaptee()));
pTarget->Request();
system("pause");
return 0;
}