【发布时间】:2015-01-22 11:32:25
【问题描述】:
我有一些类似的代码:
class Base {
virtual bool acceptsData(char*) = 0;
};
class Derived1 : public Base {
virtual bool acceptsData(char*) { /* do something */ }
};
class Derived2 : public Base {
virtual bool acceptsData(char*) { /* do something else */}
}
Base* createStuff(char* data)
{
Base* d1 = new Derived1();
if(d1->acceptsData(data))
{
return d1;
}
delete d1;
Base* d2 = new Derived2();
if(d2->acceptsData(data))
{
return d2;
}
delete d2;
// and more ...
}
// .... somewhere later
int main()
{
Base* Aclass = createStuff("abc");
}
我想摆脱这个冗长的if() ... 构造,并使用一些更通用的模式,但我仍然没有经理想出一些有用的东西。有更好的方法吗?
【问题讨论】:
-
你知道你的示例代码有可怕的错误吗?
-
是的,但它的目的更多是作为 c++ 伪代码,而不是您真正想要编译和使用的东西。
标签: c++ design-patterns factory