建造者模式和抽象工厂模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了建造者模式和抽象工厂模式相关的知识,希望对你有一定的参考价值。
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
以上是关于建造者模式和抽象工厂模式的主要内容,如果未能解决你的问题,请参考以下文章
设计模式系列-Builder模式,工厂方法模式和抽象工厂模式