Factory Pattern
在程序中使用工厂模式,让工厂生产这个物体,而不是调用这个物体的构造函数。比如代码需要table,可以调用FurnitureFactory 对象,创建一个新的table。
另一个好处是你可以不知道具体的物体,抽象了物体创建过程。可以 用多态(polymorphism)。
- car
- Toyota
- Ford
- CarFactory
- ToyotaFactory
- FordFactory
以下代码想说明:
- 不用具体知道car的层次类型,都是car而已
- 直接调用工厂的统一对外接口。
Toyotafactory myFactor;
Car *myCar= myFactory.requestCar();
Carfactory.h
// For this example, the Car class is assumed to already exist.
#include "Car.h"
class CarFactory
{
public:
CarFactory();
Car* requestCar();
int getNumCarsInProduction() const;
protected:
virtual Car* createCar() = 0;
private:
int mNumCarsInProduction;
};
class FordFactory : public CarFactory
{
protected:
virtual Car* createCar();
};
class ToyotaFactory : public CarFactory
{
protected:
virtual Car* createCar();
};
CarFactory.cpp
#include "CarFactory.h"
// Initialize the count to zero when the factory is created.
CarFactory::CarFactory() : mNumCarsInProduction(0) {}
// Increment the number of cars in production and return the new car.
Car* CarFactory::requestCar()
{
mNumCarsInProduction++;
return createCar();
}
int CarFactory::getNumCarsInProduction() const
{
return mNumCarsInProduction;
}
Car* FordFactory::createCar()
{
return new Ford();
}
Car* ToyotaFactory::createCar()
{
return new Toyota();
}
Car.h
#include <iostream>
class Car
{
public:
virtual void info() = 0;
};
class Ford : public Car
{
public:
virtual void info() { std::cout << "Ford" << std::endl; }
};
class Toyota : public Car
{
public:
virtual void info() { std::cout << "Toyota" << std::endl; }
};
CarTest.cpp
#include "CarFactory.h"
#include <vector>
#include <memory>
using namespace std;
shared_ptr<CarFactory> getLeastBusyFactory(const vector<shared_ptr<CarFactory>>& inFactories)
{
if (inFactories.size() == 0)
return nullptr;
shared_ptr<CarFactory> bestSoFar = inFactories[0];
for (size_t i = 1; i < inFactories.size(); i++) {
if (inFactories[i]->getNumCarsInProduction() <
bestSoFar->getNumCarsInProduction()) {
bestSoFar = inFactories[i];
}
}
return bestSoFar;
}
int main()
{
vector<shared_ptr<CarFactory>> factories;
// Create 3 Ford factories and 1 Toyota factory.
auto factory1 = make_shared<FordFactory>();
auto factory2 = make_shared<FordFactory>();
auto factory3 = make_shared<FordFactory>();
auto factory4 = make_shared<ToyotaFactory>();
// To get more interesting results, preorder some cars.
factory1->requestCar();
factory1->requestCar();
factory2->requestCar();
factory4->requestCar();
// Add the factories to a vector.
factories.push_back(factory1);
factories.push_back(factory2);
factories.push_back(factory3);
factories.push_back(factory4);
// Build 10 cars from the least busy factory.
for (size_t i = 0; i < 10; i++) {
shared_ptr<CarFactory> currentFactory = getLeastBusyFactory(factories);
shared_ptr<Car> theCar(currentFactory->requestCar());
theCar->info();
}
return 0;
}
LanguagageFactory
EnglishLanguageFactory, FrenchLanguageFactory都有createSpellChecker, 不需要具体知道每个spell checker是怎么做,直接调用就好了。