/**
* Car.h
*
*/
#ifndef __CAR_
#define __CAR_
#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;
}
};
#endif
/**
* 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();
}
/*
*test.cpp
*/
#include <vector>
#include "Car.h"
#include "CarFactory.h"
using namespace std;
CarFactory* getLeastBusyFactory(const vector<CarFactory*>& inFactories)
{
if (inFactories.size() == 0) return NULL;
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(int argc, char** argv)
{
vector<CarFactory*> factories;
// Create 3 Ford factories and 1 Toyota factory.
FordFactory* factory1 = new FordFactory();
FordFactory* factory2 = new FordFactory();
FordFactory* factory3 = new FordFactory();
ToyotaFactory* factory4 = new 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 (int i = 0; i < 10; i++) {
CarFactory* currentFactory = getLeastBusyFactory(factories);
Car* theCar = currentFactory->requestCar();
theCar->info();
}
system("pause");
return 0;
}
Factory methods are one way to implement virtual constructors: methods that
create objects of different types. For example, the buildCar() method creates both
Toyotas and Fords, depending on the concrete factory object on which it is called.