我正在生成一系列Step
对象,这些对象因“类型”和其中包含的数据而不同。例如:Step
对象基本上应该是如下所示的结构
{ GRAB, CASCADE_ONE, FACEUP, SOMEOTHERDATA },
{ DROP, DECK, FACEDOWN, MOREDATA, ANDSOMEMORE },
{ MOVE, 34, 89 },
其中
GRAB
,MOVE
和DROP
表示StepType
:typedef enum
{
GRAB,
DROP,
MOVE
}StepType;
如您所见,根据
StepType
,这些结构每个在StepType
之后都有可变数量的数据字段。我计划遍历这些结构的序列,并根据
StepType
字段执行特定的操作。我的第一个直觉是这些对象应该是从抽象Step
类派生的类的对象-即,我应该创建一个GrabStep
类,一个MoveStep
类和一个DropStep
类。这是一个好的设计吗?如果可以,我应该使用工厂方法来创建它们吗?如果要使用工厂方法,那么如何初始化对象中的字段?
最佳答案
您不需要此工厂模式。但是创建一个抽象的Step
类是一个好的开始:
class Step
{
private:
// The presence of a pure virtual makes this class abstract.
virtual void DoAction() = 0;
public:
virtual ~Step() {} // Needed if you are going to delete via a Step* pointer
void Action() { DoAction(); } // Template method pattern
};
// All other classes derive publicly from Step, since they all have an "is-a"
// relationship with Step (i.e. a GrabStep "is-a" Step).
class GrabStep : public Step
{
private:
void DoAction() { /* Do whatever a GrabStep does */ };
// Data relevant to GrabStep
};
class MoveStep : public Step
{
private:
void DoAction() { /* Do whatever a MoveStep does */ };
// Data relevant to MoveStep
};
class DropStep : public Step
{
private:
void DoAction() { /* Do whatever a DropStep does */ };
// Data relevant to DropStep
};
然后,您可以遍历这些东西而不必知道它们的确切类型:
// Example:
std::vector<Step*> seq; // or some other container
// Note that we are storing Step* pointers in a container instead of Step
// objects. This is needed for polymorphism to work.
// ...
seq.push_back(new GrabStep);
seq.push_back(new MoveStep);
seq.push_back(new DropStep);
// ...
for(std::vector<Step*>::iterator i = seq.begin(); i != seq.end(); ++i)
{
// Will call the proper version of DoAction() depending on the actual type.
(*i)->Action();
}
// ...
// After we are done, clean up after ourselves. This is needed because
// std::vector does not delete the pointees.
for(std::vector<Step*>::iterator i = seq.begin(); i != seq.end(); ++i)
{
delete (*i); // Safe because Step has a virtual destructor.
}
关于c++ - 这里的工厂方法合适吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3226808/