一、工厂模式
工厂模式是对简单工厂模式的优化,以汽车为例,工厂模式有以下角色
- 抽象工厂类:抽象汽车工厂
- 具体工厂类:轿车工厂类、公交工厂类
- 抽象产品类:汽车产品类
- 具体产品类:汽车、公交
各类关系图:
二、工厂模式的实现
Factory.h
#ifndef FACTORY_H
#define FACTORY_H
#include <iostream>
#include <string>
using namespace std;
//抽象产品类
class Products
{
public:
//产品方法
virtual void productMethod() = 0;
};
//car产品类
class car : public Products
{
public:
void productMethod()
{
cout << " car " << endl;
}
};
//bus产品类
class bus : public Products
{
public:
void productMethod()
{
cout << " bus " << endl;
}
};
//抽象工厂类
class BaseFactory
{
public:
virtual Products* create() = 0;
};
//car工厂类
class carFactory : public BaseFactory
{
public:
Products* create()
{
return new car();
}
};
//bus工厂类
class busFactory : public BaseFactory
{
public:
Products* create()
{
return new bus();
}
};
#endif
client.cpp
#include "Factory.h"
int main()
{
/*
使用流程:
1. 需要什么产品
2. 构建对应工厂
3. 使用对应工厂生产对应产品
4. 使用产品对应方法
*/
//生产小轿车
BaseFactory* bf = new carFactory();
Products* bp = bf->create();
bp->productMethod();
delete bf;
delete bp;
//生产公交车
bf = new busFactory();
bp = bf->create();
bp->productMethod();
delete bf;
delete bp;
return 0;
}
三、unique_ptr的优化
Factory.h
#ifndef FACTORY_H
#define FACTORY_H
#include <iostream>
#include <string>
#include <memory>
using namespace std;
//抽象产品类
class Products
{
public:
//产品方法
virtual void productMethod() = 0;
};
//car产品类
class car : public Products
{
public:
void productMethod()
{
cout << " car " << endl;
}
};
//bus产品类
class bus : public Products
{
public:
void productMethod()
{
cout << " bus " << endl;
}
};
//抽象工厂类
class BaseFactory
{
public:
virtual unique_ptr<Products> create() = 0;
};
//car工厂类
class carFactory : public BaseFactory
{
public:
unique_ptr<Products> create()
{
return unique_ptr<Products>(new car());
}
};
//bus工厂类
class busFactory : public BaseFactory
{
public:
unique_ptr<Products> create()
{
return unique_ptr<Products>(new bus());
}
};
#endif
client.cpp
//工厂模式客户端
#include "Factory.h"
int main()
{
//生产小轿车
unique_ptr<BaseFactory> bf(new carFactory());
unique_ptr<Products> bp = bf->create();
bp->productMethod();
//生产公交车
bf.reset(new busFactory());
bp = bf->create();
bp->productMethod();
return 0;
}