考慮下面的代碼:多態工廠
template <typename T>
class DrawerFactory
{
protected:
DrawerFactory() {};
private:
virtual shared_ptr<IDrawer> GetDrawer(T settings) = 0;
};
class ConcreteDrawerFactoryA : public DrawerFactory<SettingsA>
{
public:
shared_ptr<IDrawer> GetDrawer(SettingsA settingsA) override
{
if (settingsA.style == A) return make_shared<ConcreteDrawerA>(settingsA.length, settingsA.stroke, settingsA.opacity);
else return make_shared<ConcreteDrawerB>(20, .5);
};
};
class ConcreteDrawerFactoryB : public DrawerFactory<SettingsB>
{
public:
shared_ptr<IDrawer> GetDrawer(SettingsB settingsB) override
{
if (settingsB.type == TYPEC) return make_shared<ConcreteDrawerC>(settingsB.width, settingsB.height);
else return make_shared<ConcreteDrawerD>(10, 2);
};
};
我可以得到一個抽屜:
ConcreteDrawerFactoryA().GetDrawer(settingsa);
或
ConcreteDrawerFactoryB().GetDrawer(settingsb);
我希望做的是:
DrawerFactory().GetDrawer(settingsa);
DrawerFactory().GetDrawer(settingsb);
有沒有辦法設置這個,而不必不斷地爲我想添加的每個混凝土工廠添加超載到DrawerFactory
?
唯一的辦法是投''裏面GetDrawer' Settings'。更多的面向對象解決方案是讓'Settings'處理「通用」名稱 - 值對,比如'settings.getInt(「width」)' – Arkadiy
'DrawerFactory()'是沒有意義的,因爲DrawerFactory具有純虛擬方法。 .. – jpo38
jpo38:我知道它不會以我想要的方式工作,因此問題 –