您好,登錄后才能下訂單哦!
這篇文章主要講解了“java建造者模式和抽象工廠模式怎么實現”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“java建造者模式和抽象工廠模式怎么實現”吧!
1、建造者模式
一個對象的構建比較復雜,將一個對象的構建和對象的表示進行分離!!!
2、具體實現
(1)、代碼如下
#include<iostream> #include<string> using namespace std; class House{ public: void setDoor(string door){ this->m_door = door; } void setWall(string wall){ this->m_wall = wall; } void setWindow(string window){ this->m_window = window; } public: string getDoor(){ return m_door; } string getWall(){ return m_wall; } string getWindow(){ return m_window; } private: string m_door; string m_wall; string m_window; }; //請工程隊來建造房子 class Build{ public: House *setHouse(){ } private: }; int main(void){ //這樣寫不好,是客戶直接造房子; House *house = new House; house->setDoor("門"); house->setWall("墻面"); house->setWindow("窗口"); delete house; return 0; }
3、抽象工廠
只能生產一個產品;
4、具體實現
(1)、代碼如下
#include<iostream> using namespace std; class Fruit; class AbstractFactory{ public: virtual Fruit *CreateBanana() = 0; virtual Fruit *CreateApple() = 0; private: }; class Fruit{ public: virtual void sayname() = 0; private: }; class NorthBanana : public Fruit{ public: virtual void sayname(){ cout<<"我是北方香蕉"<<endl; } }; class NorthApple : public Fruit{ public: virtual void sayname(){ cout<<"我是北方蘋果"<<endl; } }; class SouthBanana : public Fruit{ public: virtual void sayname(){ cout<<"我是南方香蕉"<<endl; } }; class SouthApple : public Fruit{ public: virtual void sayname(){ cout<<"我是南方蘋果"<<endl; } }; class NorthFactory : public AbstractFactory{ public: virtual Fruit *CreateBanana(){ return new NorthBanana; } virtual Fruit *CreateApple(){ return new NorthApple; } private: }; class SouthFactory : public AbstractFactory{ public: virtual Fruit *CreateBanana(){ return new SouthBanana; } virtual Fruit *CreateApple(){ return new SouthApple; } private: }; int main(void){ Fruit *fruit = NULL; AbstractFactory *af = NULL; //--------------------------- af = new SouthFactory; fruit = af->CreateApple(); fruit->sayname(); fruit = af->CreateBanana(); fruit->sayname(); //--------------------------- af = new NorthFactory; fruit = af->CreateApple(); fruit->sayname(); fruit = af->CreateBanana(); fruit->sayname(); delete af; return 0; }
(2)、運行結果
(3)、抽象模式
缺點:抽象工廠的產品線都被寫死了;只能生產這2種產品;
感謝各位的閱讀,以上就是“java建造者模式和抽象工廠模式怎么實現”的內容了,經過本文的學習后,相信大家對java建造者模式和抽象工廠模式怎么實現這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。