设计模式之简单工厂
作者:互联网
一、适用场景
1.、工厂类负责创建的对象比较少,由于创建的对象较少,不会造成的业务逻辑太过复杂
2.、客户端只知道传入工厂类的参数,对于如何创建对象并不关心
二、示例代码
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
//抽象水果
class AbstractFruit{
public:
virtual void ShowName() = 0;
};
//苹果
class Apple : public AbstractFruit{
public:
virtual void ShowName(){
cout << "苹果!" << endl;
}
};
//香蕉
class Banana : public AbstractFruit{
public:
virtual void ShowName(){
cout << "香蕉!" << endl;
}
};
//水果工厂
class FruitFactory
{
public:
AbstractFruit* CreateFruit(string name)
{
if (name == "apple")
{
return new Apple;
}
else if (name == "banana")
{
return new Banana;
}
else
{
return NULL;
}
}
};
void test(void)
{
FruitFactory * factory = new FruitFactory;
AbstractFruit * fruit = factory->CreateFruit("apple");
fruit->ShowName();
delete fruit;
fruit = factory->CreateFruit("banana");
fruit->ShowName();
delete fruit;
delete factory;
}
int main(void)
{
test();
return 0;
}
标签:void,factory,工厂,fruit,简单,设计模式,public,ShowName,delete 来源: https://blog.csdn.net/qq_21231413/article/details/94734804