在运行时选择方法实现 [英] Choosing method implementation at runtime
问题描述
我想通过选择一种从给定集合中调用的方法来配置对象在运行时的行为。考虑一个简单的例子:
I'd like to configure the behaviour of objects at runtime by choosing a method to call out of a given set. Consider this simple example:
class Parameter;
class Conf;
class Obj {
public:
Obj( const Conf &t ): t_( t ) {}
void f( Parameter *d );
void f1( Parameter *d );
void f2( Parameter *d );
typedef void ( Obj::*Fn )( Parameter *d );
private:
const Conf &t_;
};
class Conf {
public:
Obj::Fn f;
};
void Obj::f( Parameter *d ) {
( this->*t_.f )( d );
}
通过更改 Conf :: f $ c对于给定的
Conf
对象,如果$ c>更改了配置了该对象的所有 Obj
对象的行为。
By changing Conf::f
for a given Conf
object, the behaviour of all Obj
objects configured with this is changed.
第一个问题:这是否类似于某种设计模式(好吧,这有点像方法指针策略之类的东西...)?如果是这样,我应该考虑重新设计吗?
First question: Does this resemble some design pattern (ok, it's kind of a method-pointer-strategy-thing...)? If so, should I consider a redesign?
第二个问题:我想通过使用不同的参数类来使其更加灵活。我已经通过将 Parameter
作为基类并在 fN
方法中进行类型转换来做到这一点,但这确实看起来不是最终解决方案。有什么建议吗?
Second question: I'd like to make this more flexible by using different parameter classes. I've already done this by making Parameter
a base class and doing type casting in the fN
methods, but that does not look like a final solution. Any suggestions?
推荐答案
这使我想起状态模式,考虑到状态更改时,将在另一个对象上调用方法。如果您查看Wikipedia链接的Java示例,则StateContext对象具有myState属性,该属性将更改为其他State对象以进行状态更改。
This reminds me of the State pattern, considering when the state changes, a method will be called on a different object. If you look at the Java example of the wikipedia link, the StateContext object has the myState attribute which will be changed to a different State object for state changes.
您可以执行类似的操作,从而使Obj类具有指向对象的指针/引用,该对象实现了在其实现的接口中指定的方法。然后可以通过内部逻辑或通过外部设置将内部指针/引用更改为指向不同的对象,然后调用的方法将有所不同。
You could do something similar, whereby your Obj class would have a pointer/reference to an object that implements a method specified in the interface that it implements. Then the internal pointer/reference could be changed to point to a different object, either by internal logic or by setting it externally, and then the method being called will be different.
这里有个简单的例子:
class Action
{
virtual void action() = 0;
}
class Action1 : public Action
{
virtual void action() { /* do something useful here */ }
};
class Action2 : public Action
{
virtual void action() { /* do something different here */ }
}
class Obj
{
public:
setAction(Action *a) {a_ = a;}
void action() {if(a_) a_->action();}
private:
Action *a_;
};
{
Action1 a1;
Action2 a2;
Obj o;
o.setAction(&a1);
o.action();
o.setAction(&a2);
o.action();
}
如评论中所述,这也与策略模式非常相似。
As mentioned in the comments, this is also very similar to the Strategy pattern.
这篇关于在运行时选择方法实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!