tags:

views:

114

answers:

2

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?

+6  A: 

You are looking for http://en.wikipedia.org/wiki/Factory_method_pattern

Johannes Schaub - litb
+2  A: 

First, you should use a factory or factory method as litb has mentioned.

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.

Gamecat