您好,登錄后才能下訂單哦!
1、工廠模式
面向抽象類編程,底下可以接N多個(gè)生產(chǎn)某種的具體工廠;
簡單工廠模式:專門定義一個(gè)類來負(fù)責(zé)創(chuàng)建其它類的實(shí)例,被創(chuàng)建的實(shí)例通常都具有共同的父類;
2、具體實(shí)現(xiàn)
(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: }; //添加新的產(chǎn)品 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)、運(yùn)行結(jié)果
(3)、工廠模式
擴(kuò)展性不好;
3、原型模式
提供一個(gè)clone()接口,讓普通對(duì)象擁有自我復(fù)制的功能!
相當(dāng)于拷貝構(gòu)造函數(shù)的編寫;(當(dāng)有成員為指針時(shí))這個(gè)牽扯深拷貝和淺拷貝的問題;
4、具體實(shí)現(xiàn)
(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; //此時(shí)就會(huì)牽扯深拷貝的問題 }; int main(void){ Cplus *c1 = new Cplus("張三", 32); c1->printT(); Person *c2 = c1->clone(); c2->printT(); return 0; }
(2)、運(yùn)行結(jié)果
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。