クラス StructComponent のコンストラクターは、異なるロジックを使用して、info のパスイン オブジェクトの型に基づいてメンバー変数を初期化します。ここでは、キャストを使用して、パスイン パラメーターを適切なサブクラス オブジェクトに変換します。
class StructComponent
{
public:
StructComponent(const ClassA& info)
{
if (info.getType() == CLASS_B)
{
const ClassC& classC = dynamic_cast<const ClassC&> info;
...
apply a different logic for ClassB and init member accordingly
} else if (info.getType() == CLASS_C) {
apply a different logic for others
...
} else {
apply default
}
}
}
class ClassA
{
public:
ClassA(...)
{
m_shp = CreateStructComponent();
}
virtual boost::shared_ptr<StructComponent> CreateStructComponent()
{
return boost::shared_ptr<StructComponent> (new StructComponent(*this));
}
...
int getType() const { return CLASS_A; }
protected:
boost::shared_ptr<StructComponent> m_shp;
}
class ClassB : public ClassA
{
public:
...
virtual boost::shared_ptr<StructComponent> CreateStructComponent()
{
return boost::shared_ptr<StructComponent> (new StructComponent(*this));
}
...
int getType() const { return CLASS_B; }
}
class ClassC : public ClassA
{
public:
...
virtual boost::shared_ptr<StructComponent> CreateStructComponent()
{
return boost::shared_ptr<StructComponent> (new StructComponent(*this));
}
...
int getType() const { return CLASS_C; }
}
Q1> 潜在的な設計上の問題を無視したコードは正しいですか?
Q2> ClassA のすべてのサブクラスが CreateStructComponent 関数の同じ実装本体を持っていると仮定します。次のように同じコードを繰り返し実行しないようにスペースを節約できる方法はありますか?
return boost::shared_ptr<StructComponent> (new StructComponent(*this));
Q3> 使用できるより良いデザインはありますか? たとえば、StructComponent でキャストを無視できる方法はありますか?