系统的数据和行为都正确,但接口不符时,我们应该考虑用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。
适配器主要分为类适配器和对象适配器
这里主要讲对象适配器
-
class Target{
-
public:
-
virtual void Request()
-
{
-
cout<<\"普通请求\"<<endl;
-
}
-
};
-
-
class Adaptee //需要适配的类
-
{
-
public:
-
void SpecificRequest()
-
{
-
cout<<\"特殊请求\"<<endl;
-
}
-
};
-
-
class Adapter:public Target
-
{
-
private:
-
Adaptee adaptee;
-
public:
-
void Request()
-
{
-
adaptee.SpecificRequest();
-
}
-
};
-
-
int main(void)
-
{
-
Target target=new Adapter();
-
target.Request();
-
return 0;
-
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29012686/viewspace-1128805/
,如需转载,请注明出处,否则将追究法律责任。