同じ階層に異なるクラスを作成するファクトリ関数を検討しています。通常、ファクトリは通常次のように実装されることを理解しています。
Person* Person::Create(string type, ...)
{
// Student, Secretary and Professor are all derived classes of Person
if ( type == "student" ) return new Student(...);
if ( type == "secretary" ) return new Secretary(...);
if ( type == "professor" ) return new Professor(...);
return NULL;
}
さまざまな条件をハードコードする必要がないように、プロセスを自動化できる方法を考えようとしています。
これまでのところ、私が考えることができる唯一の方法は、マップとプロトタイプ パターンを使用することです。
マップは、最初の要素に型文字列を保持し、2 番目の要素にクラス インスタンス (プロトタイプ) を保持します。
std::map<string, Person> PersonClassMap;
// This may be do-able from a configuration file, I am not sure
PersonClassMap.insert(make_pair("student", Student(...)));
PersonClassMap.insert(make_pair("secondary", Secretary(...)));
PersonClassMap.insert(make_pair("professor", Professor(...)));
関数は次のようになります。
Person* Person::Create(string type)
{
map<string, Person>::iterator it = PersonClassMap.find(type) ;
if( it != PersonClassMap.end() )
{
return new Person(it->second); // Use copy constructor to create a new class instance from the prototype.
}
}
残念ながら、プロトタイプ メソッドは引数をサポートしていないため、ファクトリによって作成されるクラスを毎回同じにしたい場合にのみ機能します。
いい方法でそれを行うことが可能かどうか誰かが知っていますか、それともファクトリ関数にこだわっていますか?