您好,登錄后才能下訂單哦!
1、工廠模式
面向抽象類編程,底下可以接N多個生產某種的具體工廠;
簡單工廠模式:專門定義一個類來負責創建其它類的實例,被創建的實例通常都具有共同的父類;
2、具體實現
(1)、代碼如下
#include<iostream> using namespace std; class Fruit{ public: virtual void sayname() = 0; private: }; class Banana : public Fruit{ public: void sayname(){ cout<<"我是香蕉"<<endl; } private: }; class Apple : public Fruit{ public: void sayname(){ cout<<"我是蘋果"<<endl; } private: }; class AbFactory{ public: virtual Fruit *CreateProduct() = 0; private: }; class BananaFactory : public AbFactory{ public: virtual Fruit *CreateProduct(){ return new Banana; } private: }; class AppleFactory : public AbFactory{ public: virtual Fruit *CreateProduct(){ return new Apple; } private: }; //添加新的產品 class Pear : public Fruit{ public: void sayname(){ cout<<"我是 pear"<<endl; } private: }; class PearFactory : public AbFactory{ public: Fruit *CreateProduct(){ return new Pear; } private: }; int main(void){ AbFactory *factory = NULL; Fruit *fruit = NULL; //吃香蕉 factory = new BananaFactory; fruit = factory->CreateProduct(); fruit->sayname(); //吃梨 factory = new PearFactory; fruit = factory->CreateProduct(); fruit->sayname(); delete factory; return 0; }
(2)、運行結果
(3)、工廠模式
擴展性不好;
3、原型模式
提供一個clone()接口,讓普通對象擁有自我復制的功能!
相當于拷貝構造函數的編寫;(當有成員為指針時)這個牽扯深拷貝和淺拷貝的問題;
4、具體實現
(1)、代碼如下
#include<iostream> #include<string> using namespace std; class Person{ public: virtual Person *clone() = 0; virtual void printT() = 0; private: }; class Cplus : public Person{ public: Cplus(){ m_name = ""; m_age = 0; } Cplus(string name, int age){ m_name = name; m_age = age; } virtual void printT(){ cout<<"m_name:"<<m_name<<" "<<"m_age:"<<m_age<<endl; } virtual Person *clone(){ Cplus *tmp = new Cplus; *tmp = *this; return tmp; } private: string m_name; int m_age; char *p; //此時就會牽扯深拷貝的問題 }; int main(void){ Cplus *c1 = new Cplus("張三", 32); c1->printT(); Person *c2 = c1->clone(); c2->printT(); return 0; }
(2)、運行結果
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。