共通のベースから派生したさまざまなオブジェクトの束をファイルに保存して再読み込みしています。明らかに、再読み込み時に正しいオブジェクト タイプを作成するために、クラス名 (または同様のもの) を保存する必要があります。
保存は簡単です:
class Base
{
virtual string className() const = 0;
void saveToFile()
{
write(className());
... other writing stuff
}
}
class Derived1: public Base
{
string className() const { return "Derived1"; };
...
}
class Derived2: public Base
{
string className() const { return "Derived2"; };
...
}
そして、文字列を複製することを気にしなければ、ロードは簡単です...
static Base * Base::factory(const String &cname)
{
if (cname == "Derived1")
return new Derived1;
else if (cname == "Derived2")
return = new Derived2;
else ...
}
void load()
{
String cname = readString();
Base * obj(Base::factory(cname);
obj->readIt();
}
But, the duplicated strings offends my sense of DRY: Ideally, className()
could be static virtual
but that isn't allowed. I have a feeling that I'm missing an obvious 'clean' way round this, but I can't see it yet. Any suggestions?
Note: OK, code slightly tweaked using a factory method. Note that this doesn't actually answer the problem!
Note #2: The code above isn't trying to be a perfect representation of the ultimate factory pattern. I'm not concerned with unwanted linkage between base and derived classes, or potential difficulties in extending the hierarchy. I'm looking for answers that will simplify the code rather than complicate it.