gpt4 book ai didi

c++ - 重构 switch 语句的设计模式

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:17:38 31 4
gpt4 key购买 nike

标题中有类似下面的内容

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++ 语言功能重新设计)来重构此代码的最佳方法是什么?

我读到命令模式通常用于重构 switch 语句,但这似乎只适用于在算法之间进行选择以执行任务时。这是适用工厂模式还是抽象工厂模式的地方(我都不是很熟悉)?双重 dispatch ?

我已尝试尽可能多地省略无关紧要的上下文,但如果我遗漏了一些重要的内容,请告诉我,我会进行编辑以包含它。此外,我找不到任何类似的东西,但如果这是重复的,请将我重定向到相应的 SO 问题。

最佳答案

你可以使用 Factory Method根据您从流中获取的值创建基类(派生类)的正确实现的模式。

关于c++ - 重构 switch 语句的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3407409/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com