Currently, I have an interface and several concrete implementation class, and I got string
type user input. I want to new
corresponding class according to user input. What is the best practice to do these stuff?
It seems that the "factory patten" can be used for this. Now, I use an enum
, an unordered_function
and a specific function to handle it, the code is like below:
class IStrategy{};
class A : public IStrategy{};
class B : public IStrategy{};
class C : public IStrategy{};
class D : public IStrategy{};
enum StrategyEnum
{
A = 0,
B,
C,
D,
};
const std::unordered_map<std::string, StrategyEnum> ms_lut{
{"A", A},
{"B", B},
{"C", C},
{"D", D}};
Strategy* get_strategy(StrategyEnum s)
{
Strategy* s;
switch(s)
{
case A:
s = new A;
break;
case B:
s = new B;
break;
case C:
s = new C;
break;
case D:
s = new C;
break;
default:
cerr << "Unsupported strategy!" << endl;
}
return s;
}
What's more, in my current situation, all derived class have the same constructor parameter, what if different class has different constructor parameter?
Aucun commentaire:
Enregistrer un commentaire