您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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)、运行结果
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。