Have a interface
有一个界面
class abc {
public:
virtual int foo() = 0;
...
}
class concrete1: public abc {
public:
int foo() {
..
}
class concrete2 : public abc {
public:
int foo() {
..
}
}
Now in my main program I need to construct classes based upon a value of a variable
现在在我的主程序中,我需要根据变量的值构造类
abc *a;
if (var == 1)
a = new concrete1();
else
a = new concrete2();
Obviously I don't want these two lines everywhere in the program (please note I have simplified here so that things are clear). What design pattern should I be using if there are any?
显然我不希望程序中到处都是这两行(请注意我已经在这里简化了以便事情清楚)。如果有的话,我应该使用什么设计模式?
2 个解决方案
#1
You are looking for http://en.wikipedia.org/wiki/Factory_method_pattern
您正在寻找http://en.wikipedia.org/wiki/Factory_method_pattern
#2
First, you should use a factory or factory method as litb has mentioned.
首先,您应该使用litb提到的工厂或工厂方法。
But in addition to that I advise you to use an enum, or at least symbolic constants to determine which class to instantiate. This is much easier to read, and it allows you to build safeguards for unexpected values.
但除此之外,我建议您使用枚举,或至少使用符号常量来确定要实例化的类。这更容易阅读,它允许您为意外值构建安全措施。
#1
You are looking for http://en.wikipedia.org/wiki/Factory_method_pattern
您正在寻找http://en.wikipedia.org/wiki/Factory_method_pattern
#2
First, you should use a factory or factory method as litb has mentioned.
首先,您应该使用litb提到的工厂或工厂方法。
But in addition to that I advise you to use an enum, or at least symbolic constants to determine which class to instantiate. This is much easier to read, and it allows you to build safeguards for unexpected values.
但除此之外,我建议您使用枚举,或至少使用符号常量来确定要实例化的类。这更容易阅读,它允许您为意外值构建安全措施。