这篇文章主要讲解了“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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。