我想實現的是由在C++私有構造
- 一個工廠類工廠模式工廠模式
- 的抽象類與受保護的構造
- 繼承類有私有構造函數和虛擬公共 析構函數。
我想確保
- 沒有其他人比工廠不能創建任何實例
- 如果一個新的繼承類的定義也不會要求對接口類,並已進行任何修改定義的繼承類。 Juts新類實現並添加到工廠類中創建方法。
我也不想爲每個繼承類編寫類似代碼(比如每個被繼承類的靜態工廠方法),並讓未來的開發人員爲工廠連接做很多工作。
即與pseduo代碼
class Factory;
class Interface
{
protected:
Interface(){/*Do something*/};
public:
virtual ~Interface(){/*Do something*/}
/*I wish I could do below and it is valid for all inherited
classes but friendship is not inherited in C++*/
//friend Interface* Factory::create(Type)
};
class InheritedA:public Interface
{
private:
InheritedA(){/*Do something*/};
public:
virtual ~InheritedA(){/*Do something*/}
/*I dont want to do below two lines for every inherited class*/
//friend Interface Factory::create(Type)
//public: Interface* factoryInheritedA(){return new InheritedA();}
};
class InheritedB:public Interface
{
private:
InheritedB(){/*Do something*/};
public:
virtual ~InheritedA(){/*Do something*/}
};
class Factory
{
static Interface* create(Interface type)
{
switch(type)
{
case A:
return new InheritedA();
case B:
return new InheritedB();
default:
//exceptions etc
}
}
}
int main()
{
Interface* I = Factory::create(A/*or B*/);
return 0;
}
上面的代碼是我放出來的cloest。任何建議(C++的專業,不同的設計,...)都是值得歡迎的。
你忘了寫一個問題。 – Lemonov
爲什麼你需要這一切?聽起來像Javaesque。這可能是XY問題的一個例子。 – Shoe
@UzorTuTuEjt我寫了我想要做的限制。我真的不明白爲什麼需要問句 – ataman