Design question for an abstract base class?

You have an 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 build classes based on the value of a variable

abc *a;
if (var == 1)
   a = new concrete1();
else
   a = new concrete2();

      

Obviously, I don't want these two lines all over the place in the program (note that I am simplified here to keep things clear). What design pattern should you use, if any?

0
c ++ design


source to share


2 answers


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



+6


source to share


First, you have to use the factory or factory method mentioned in it.



But in addition to that, I advise you to use an enumeration, or at least symbolic constants, to determine which class to create. It is much easier to read and allows you to create guarantees for unexpected values.

+2


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics