我花了大约 2 个小时阅读了很多与工厂相关的主题,但我仍然不确定这是否是正确的方法。
事情是这样的:我有一个Enemy 类,它包含成员变量,例如name_ 和health_。我想用这些成员变量的不同值创建它的实例,我的第一种方法是从具有以下属性的静态数组中获取参数:
Enemy::Enemy(int type) : name_(properties[type].name),
health_(properties[type].health)
{
...
}
这里的问题是我无法检查数组 properties 是否已经填满。我必须通过调用静态 Enemy::initArray() 函数从外部检查它,但这会破坏 Enemy 类的封装。
是时候创建一个工厂,在它的构造函数中初始化 properties 数组吗?然后创建敌人:
Enemy* EnemyFactory::create(type);
我读到,当您具有复杂的类层次结构时,通常会创建工厂,或者工厂调用者只需要知道所创建类的接口(interface)。我只需要数组创建和验证的封装。有没有“更轻”的解决方案?
编辑: 我会尽量说得更清楚:
1.) 我想我知道如何创建工厂。主要问题是是否有替代方案!
2.) 我不想在对象内部设置属性,而是使用初始化列表。如果我做前者,我可以只检查构造函数中的数组,根本不需要工厂。
最佳答案
基本上有三个选项:
每个人都可以自由指定
Enemy
的初始名称和生命值,它接受这两个作为其(公共(public))构造函数中的参数。Enemy
类构造函数将“Enemy ID”映射到适当的属性值。当您需要验证“敌人 ID”的有效性和/或映射的存在,同时还对属性使用初始化列表时,这种方法就会出现问题。这通常通过添加一个虚拟成员/基类来解决,该成员/基类通过调用验证函数进行初始化。
这通常看起来像这样:
class Enemy
{
bool dummy_must_be_first;
public:
Enemy(int type) : dummy_must_be_first(validate(type), name(properties[type].name), health(properties[type].health) {}
private:
bool validate(int type)
{
// ensure properties is initialised and verify type is within range...
// on failure, throw an exception
return true;
}
string name;
int health;
};
- 您使用工厂函数执行“敌人 ID”与用于初始化
Enemy
对象的属性之间的映射。
不需要单独的工厂类。为此,工厂方法就足够了:
class Enemy
{
private:
Enemy(string name_, int health_) : name(name_), health(health_) {}
string name;
int health;
public:
static auto_ptr<Enemy> createEnemy(int type)
{
// ensure properties is initialised and verify type is within range...
return auto_ptr<Enemy>(new Enemy(properties[type].name, properties[type].health));
}
};
关于c++ - 使用断言参数存在的参数化类创建。使用工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4156029/