Item 29. Virtual Constructors and PrototypeItem 30. Factory Method
Item 29. Virtual Constructors and Prototype
Virtual Constructors?
C++沒有Virtual Constructors這個概念。但有的情況下又需要這個功能,即在多態(tài)的時候能夠創(chuàng)建出一個跟指針的動態(tài)類型相同的一個對象。既然是多態(tài)就要考慮虛函數(shù),在虛函數(shù)中調用構造函數(shù)不就行了么?是的,這就是設計模式中的Prototype的解決方案:一個clone()的虛成員函數(shù)。
class Meal {
?? public:
???? virtual ~Meal();
???? virtual void eat() = 0;
???? virtual Meal *clone() const = 0;
???? //...
};
class Spaghetti : public Meal {
?? public:
???? Spaghetti( const Spaghetti & ); // copy ctor
???? void eat();
???? Spaghetti *clone() const
???????? { return new Spaghetti( *this ); } // call copy ctor
???? //...
};
const Meal *m = new Spaghetti;
Meal *myMeal = m->clone();
Item 30. Factory Method
哦,《設計模式》一書的更詳細。
轉載于:https://www.cnblogs.com/aiwz/archive/2005/04/15/6333222.html
總結
以上是生活随笔為你收集整理的Item 29. Virtual Constructors and PrototypeItem 30. Factory Method的全部內容,希望文章能夠幫你解決所遇到的問題。