这篇文章主要介绍了C++的工厂模式怎么实现的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇C++的工厂模式怎么实现文章都会有所收获,下面我们一起来看看吧。
简单工厂模式:创建型模式/静态工厂方法模式,不属于23种设计模式,
就是实实在在的构造一个工厂类(高內聚,新增添的话,必须修改原有代码,而不是扩充原有代码),不易扩充;
作用:用一个类去创建其它类,但都有一个接口(面向抽象类编程);
(1)、代码实现
#include<iostream>
#include<string.h>
using namespace std;
class Fruit{
public:
virtual void getFruit() = 0;
private:
};
class Banana : public Fruit{
public:
virtual void getFruit(){
cout<<"我是香蕉......"<<endl;
}
private:
};
class Apple : public Fruit{
public:
virtual void getFruit(){
cout<<"我是苹果......"<<endl;
}
private:
};
class Factory{
public:
Fruit *create(const char *p){
if(strcmp(p, "banana") == 0){
return new Banana;
}else if(strcmp(p, "apple") == 0){
return new Apple;
}else{
cout<<"不支持"<<endl;
}
}
private:
};
int main(void){
Factory *f = new Factory;
Fruit *fruit = NULL;
//工厂生产香蕉
fruit = f->create("banana");
fruit->getFruit();
//工厂生产苹果
fruit = f->create("apple");
fruit->getFruit();
delete f;
return 0;
}
(2)、运行结果
关于“C++的工厂模式怎么实现”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“C++的工厂模式怎么实现”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。