gpt4 book ai didi

c++ - 使用什么模式将对象创建与其类分开

转载 作者:搜寻专家 更新时间:2023-10-31 01:55:38 28 4
gpt4 key购买 nike

假设我有一个 Foo 类,它有很多内部变量,只有一个构造函数和非修改方法。内部变量值的计算涉及状态变量和复杂函数,因此不应成为 Foo 的一部分。因此,我创建了一个执行微积分的类 FooCreator,并最终创建了 Foo。

首先我在 FooCreator 中单独实现了创建 Foo 所必需的所有成员变量,并添加了一个 createFoo() 函数,但最后 FooCreator 几乎变成了 Foo 的拷贝加上一些状态变量。

接下来,我决定让 FooCreator 继承自 Foo,这样可以节省大量的输入,但是这感觉不像是一个干净的解决方案,因为要获得某物。我必须使 Foo 的成员变量受到保护而不是私有(private)的,因此向其他用户公开的内容比我想要的要多。除了创建之外,不应将 Foo 用作基类。

我看过工厂模式,但这似乎和构建器一样大材小用。这个问题肯定会很普遍。那么处理这个问题的正确方法是什么?

一些代码示例如下所示:

class Foo{
private: //protected for second case
int mVal;
State mState;
ComplexStuff mStuff;
//...

public:
Foo():mVal(),mState(),mStuff(){}
Foo(int val, State const& state, ComplexStuff const& stuff):
mVal(val),mState(state),mStuff(stuff){}
bool loadFromFile();

bool evalStateTransition(State const& formerState) const{/*....*/}
bool someTest(int) const{/*....*/};
GraphicItem* visualize() const{/* ....*/};
//...
};

class FooCreator{
private:
int mVal;
State mState;
ComplexStuff mStuff;

StuffVisualizer mStuffVis;
Paramset mParams;
//...

public:
FooCreator(Paramset const& set):
mVal(),mState(),mStuff(),mStuffVis(),mParams(set){}
constructState(int, int, int);
gatherStuff1(File file1);
Foo createFoo();

int evalStateTransition(State const& formerState) const{
/*same long code as in Foo*/
}
bool someTest(int) const{ /*same long code as in Foo*/}
GraphicItem* visualize() const{ /*same long code as in Foo*/}
//...
};

class FooCreator2 : public Foo{
private:
StuffVisualizer mStuffVis;
Paramset mParams;
//...

public:
FooCreator(Paramset const& set):Foo(),mParams(set){}
constructState(int, int, int);
gatherStuff1(File file1);
Foo createFoo();
};

最佳答案

It can be good to keep complex logic out of the constructor .但是,如果您不想使用FactoryBuilder 模式,那么您可以提取一个ParameterObject。 .

如果您需要使用 Foo 中的方法来创建实例,那么也许您应该尝试将 Foo 拆分为两个类。

关于c++ - 使用什么模式将对象创建与其类分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8231955/

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