本文共 1498 字,大约阅读时间需要 4 分钟。
工厂模式中使用了多态的原理,来将具体实现和接口进行有效的解耦合,符合开闭原则和依赖倒置原则
需要新加功能的时候不需要对原有代码进行修改。
抽象类human和抽象类factory就是调用接口,而实际的生产过程通过factory的子类(如boyfactory)来new
一个具体的human(如:boy)子类然后返回一个human父类的指针完成,如下图:
具体的代码如下:
- #include<iostream>
-
- using namespace std;
- //工厂模式新增功能并不会修改原有代码符合开闭原则
- //使用多态实现
- //纯虚拟接口
- class human
- {
- public:
- virtual void getman(void) = 0;
- virtual ~human()
- {
- //cout<<"4:"<<endl;
- }
- };
-
- class factory
- {
- public:
- virtual human* greman(void) = 0;
- virtual ~factory()
- {
- // cout<<"3:"<<endl;
- }
- };
-
- /////boy
- class boy:public human
- {
- public:
- virtual void getman(void)
- {
- cout<<"I'M BOY!"<<endl;
- }
- virtual ~boy()
- {
- // cout<<"2:"<<endl;
- }
- };
-
- class boyfactory:public factory
- {
- private:
- boy* p;
- public:
- virtual human* greman(void) //负责生产boy言外之意就是调用一个new来new出内存空间
- {
- p = new boy;
- return p;
- }
- virtual ~boyfactory()
- {
- // cout<<"1:"<<endl;
- delete p;
- }
- };
-
- //后来新建的woman工厂和woman定义
- //////////////woman
-
- class woman:public human
- {
- public:
- virtual void getman(void)
- {
- cout<<"I'M woman!"<<endl;
- }
- virtual ~woman()
- {
- // cout<<"5:"<<endl;
- }
- };
-
- class womanfactory:public factory
- {
- private:
- woman* p;
- public:
- virtual human* greman(void) //负责生产woman言外之意就是调用一个new来new出内存空间
- {
- p = new woman;
- return p;
- }
- virtual ~womanfactory()
- {
- //cout<<"6:"<<endl;
- delete p;
- }
- };
-
- ///////////////////////
-
- int main(void)
- {
- //生产boy
- factory* fa1= new boyfactory;
- human* hm1 = NULL;
- hm1 = fa1->greman();
- hm1->getman();
- delete fa1;
- //生产woman
- factory* fa2= new womanfactory;
- human* hm2 = NULL;
- hm2 = fa2->greman();
- hm2->getman();
- delete fa2;
-
- cout<<"hello!"<<endl;
- }
转载地址:http://ovmix.baihongyu.com/