首页 > 代码库 > 建造者模式和抽象工厂模式
建造者模式和抽象工厂模式
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种产品;
本文出自 “wait0804” 博客,请务必保留此出处http://wait0804.blog.51cto.com/11586096/1885893
建造者模式和抽象工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。