前文回顾
单例模式(一)
单例模式(二)
观察者模式
简单工厂模式
前言
工厂模式通常适用于需要创建大量对象的情况,若仅需要一个对象,直接 new 即可。
对于简单工厂模式,当需要增加新的产品时,需要对工厂类进行修改,违背了“开闭原则:对修改关闭、对扩展开发”。
工厂方法模式是对简单工厂的进一步抽象和封装。
实现举例
- 产品抽象基类
class Animal
{
public:
virtual ~Animal(){}
virtual void show() = 0;
};
- 产品派生类
①.Dog 类
#include "animal.h"
#include <iostream>
using namespace std;
class Dog : public Animal
{
public:
Dog(){};
void show() override
{
cout << "汪汪~"<<endl;
}
static Animal * getDog()
{
return new Dog();
}
};
②.Cat 类
#include "animal.h"
#include <iostream>
using namespace std;
class Cat : public Animal
{
public:
Cat(){}
void show() override
{
cout << "喵~"<<endl;
}
static Animal * getCat()
{
return new Cat();
}
};
- 工厂抽象基类
#include "animal.h"
class AnimalFactory
{
public:
AnimalFactory(){}
virtual ~AnimalFactory(){}
virtual Animal *CreateAnimal() = 0;
};
- 工厂派生类
①.Dog 工厂类
include "animalfactory.h"
#include "dog.h"
class DogFactory : public AnimalFactory
{
public:
DogFactory(){};
Animal * CreateAnimal() override
{
return new Dog();
}
};
②.Cat 工厂类
#include "animalfactory.h"
#include "cat.h"
class CatFactory : public AnimalFactory
{
public:
CatFactory() {};
Animal * CreateAnimal() override
{
return new Cat();
}
};
- 客户端调用
#include "dogfactory.h"
#include "catfactory.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//创建工厂
AnimalFactory * factory = new DogFactory();
//创建对象
Animal * dog = factory->CreateAnimal();
dog->show();
delete dog;
delete factory;
//更换工厂
factory = new CatFactory();
Animal *cat = factory->CreateAnimal();
cat->show();
delete cat;
delete factory;
return a.exec();
}