我们可以使用函数指针创建适配器模式吗? [英] Can we create an Adapter patterns using function pointers?
本文介绍了我们可以使用函数指针创建适配器模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图有一个Adapter类,它有一个函数指针(比如fnPtr)。并且基于不同的Adaptee类,fnPtr将被赋予相应的适配器功能。
以下是代码片段:
I was trying to have an Adapter class, which has a Function Pointer (say fnPtr). And based on different Adaptee classes the fnPtr will be assigned with corresponding adaptee`s function.
Following is the code snippet:
class AdapteeOne
{
public:
int Responce1()
{
cout<<"Respose from One."<<endl;
return 1;
}
};
class AdapteeTwo
{
public:
int Responce2()
{
cout<<"Respose from Two."<<endl;
return 2;
}
};
class Adapter
{
public:
int (AdapteeOne::*fnptrOne)(void);
int (AdapteeTwo::*fnptrTwo)(void);
Adapter(AdapteeOne* adone)
{
fnptrOne = &(AdapteeOne::Responce1);
this->*fnptrOne();
}
Adapter(AdapteeTwo adtwo)
{
fnptrTwo = &(AdapteeTwo::Responce2);
}
};
void main()
{
Adapter* adpter = new Adapter(new AdapteeOne());
/////Place to call function pointers of Adapter class
P;
}
现在我面临的问题是在main()函数中。我没有办法调用Adapter的函数指针(fnptrOne和fnptrTwo)。
请告诉我这是否是正确/可行的适配器模式?
Now the problem i am facing is in the main() function. I am not getting any way to call Adapter`s function pointers (fnptrOne and fnptrTwo).
Kindly let me know whether this is a correct/viable Adapter pattern?
推荐答案
您的适配器可能提供一个公共方法,比如执行
,它依次使用fnptrOne
或fnptrTwo
,基于其内部状态(在实例化时在被调用的ctor上)。
Your adapter might provide a public method, sayexecute
that in turns usesfnptrOne
, orfnptrTwo
, based on its internal state (that is on the called ctor at instantiation).
这篇关于我们可以使用函数指针创建适配器模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文