我有一些像在头设计模式重构switch语句
class MsgBase
{
public:
unsigned int getMsgType() const { return type_; }
...
private:
enum Types { MSG_DERIVED_1, MSG_DERIVED_2, ... MSG_DERIVED_N };
unsigned int type_;
...
};
class MsgDerived1 : public MsgBase { ... };
class MsgDerived2 : public MsgBase { ... };
...
class MsgDerivedN : public MsgBase { ... };
以下,并用作
MsgBase msgHeader;
// peeks into the input stream to grab the
// base class that has the derived message type
// non-destructively
inputStream.deserializePeek(msgHeader);
unsigned int msgType = msgHeader.getMsgType();
MsgDerived1 msgDerived1;
MsgDerived2 msgDerived2;
...
MsgDerivedN msgDerivedN;
switch(msgType)
{
case MSG_DERIVED_1:
// fills out msgDerived1 from the inputStream
// destructively
inputStream.deserialize(msgDerived1);
/* do MsgDerived1 processing */
break;
case MSG_DERIVED_2:
inputStream.deserialize(msgDerived2);
/* do MsgDerived1 processing */
break;
...
case MSG_DERIVED_N:
inputStream.deserialize(msgDerivedN);
/* do MsgDerived1 processing */
break;
}
这似乎是这将是相当普遍的良好形势的类型适合重构。应用设计模式(或基本的C++语言特性重新设计)来重构此代码的最佳方式是什么?
我读过Command模式通常用于重构switch语句,但似乎只适用于在执行任务的算法之间进行选择。这是一个工厂还是抽象工厂模式适用的地方(我对此不是很熟悉)?双派遣?
我试图忽略尽可能多的无关紧要的上下文,但如果我错过了一些重要的事情,请让我知道,我将编辑以包含它。此外,我找不到任何类似的东西,但如果这是重复的,只是将我重定向到适当的SO问题。
访客模式很适合替换像这样的开关。 – neoneye 2010-08-04 16:01:55
@neoneye:访客模式基于两个现有对象的动态类型实现双重调度。在这种情况下,我们需要确定要创建哪种类型的对象。 – 2010-08-04 16:42:26