工厂模式和原型模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了工厂模式和原型模式相关的知识,希望对你有一定的参考价值。
1、工厂模式
面向抽象类编程,底下可以接N多个生产某种的具体工厂;
简单工厂模式:专门定义一个类来负责创建其它类的实例,被创建的实例通常都具有共同的父类;
2、具体实现
(1)、代码如下
#include<iostream> using namespace std; class Fruit{ public: virtual void sayname() = 0; private: }; class Banana : public Fruit{ public: void sayname(){ cout<<"我是香蕉"<<endl; } private: }; class Apple : public Fruit{ public: void sayname(){ cout<<"我是苹果"<<endl; } private: }; class AbFactory{ public: virtual Fruit *CreateProduct() = 0; private: }; class BananaFactory : public AbFactory{ public: virtual Fruit *CreateProduct(){ return new Banana; } private: }; class AppleFactory : public AbFactory{ public: virtual Fruit *CreateProduct(){ return new Apple; } private: }; //添加新的产品 class Pear : public Fruit{ public: void sayname(){ cout<<"我是 pear"<<endl; } private: }; class PearFactory : public AbFactory{ public: Fruit *CreateProduct(){ return new Pear; } private: }; int main(void){ AbFactory *factory = NULL; Fruit *fruit = NULL; //吃香蕉 factory = new BananaFactory; fruit = factory->CreateProduct(); fruit->sayname(); //吃梨 factory = new PearFactory; fruit = factory->CreateProduct(); fruit->sayname(); delete factory; return 0; }
(2)、运行结果
(3)、工厂模式
扩展性不好;
3、原型模式
提供一个clone()接口,让普通对象拥有自我复制的功能!
相当于拷贝构造函数的编写;(当有成员为指针时)这个牵扯深拷贝和浅拷贝的问题;
4、具体实现
(1)、代码如下
#include<iostream> #include<string> using namespace std; class Person{ public: virtual Person *clone() = 0; virtual void printT() = 0; private: }; class Cplus : public Person{ public: Cplus(){ m_name = ""; m_age = 0; } Cplus(string name, int age){ m_name = name; m_age = age; } virtual void printT(){ cout<<"m_name:"<<m_name<<" "<<"m_age:"<<m_age<<endl; } virtual Person *clone(){ Cplus *tmp = new Cplus; *tmp = *this; return tmp; } private: string m_name; int m_age; char *p; //此时就会牵扯深拷贝的问题 }; int main(void){ Cplus *c1 = new Cplus("张三", 32); c1->printT(); Person *c2 = c1->clone(); c2->printT(); return 0; }
(2)、运行结果
本文出自 “wait0804” 博客,请务必保留此出处http://wait0804.blog.51cto.com/11586096/1885891
以上是关于工厂模式和原型模式的主要内容,如果未能解决你的问题,请参考以下文章