CppRpnCalculatorAbstractFactoryPatternExample

<--Back

Abstract Factory Pattern Example
This section has an example of an abstract factory and two concrete implementations. The abstract factory returns math operators used by a calculator. The operators are examples of the Strategy pattern, aka function object, functor.

Here's the abstract factory class: code format="cpp"
 * MathOperatorFactory.h**
 * 1) ifndef MATHOPERATORFACTORY_H
 * 2) define MATHOPERATORFACTORY_H

class MathOperator;


 * 1) include

class MathOperatorFactory { public: MathOperatorFactory; virtual ~MathOperatorFactory; virtual MathOperator& getOperatorNamed(const std::string& operatorName) = 0; };

code
 * 1) endif

code format="cpp"
 * MathoOperatorFactory.cpp**


 * 1) include "MathOperatorFactory.h"

MathOperatorFactory::MathOperatorFactory(void) { }

MathOperatorFactory::~MathOperatorFactory(void) { } code

Here's a basic factory that provides MathOperators using conditional and static variables within a method: code format="cpp"
 * IfBasedMathOperatorFactory.cpp**
 * 1) include "IfBasedMathOperatorFactory.h"
 * 2) include "Plus.h"
 * 3) include "Minus.h"
 * 4) include "Multiply.h"
 * 5) include "Divide.h"
 * 6) include "Factorial.h"

IfBasedMathOperatorFactory::IfBasedMathOperatorFactory{}

IfBasedMathOperatorFactory::~IfBasedMathOperatorFactory{}

MathOperator &IfBasedMathOperatorFactory::getOperatorNamed(const std::string &operatorName) { static Plus plus; static Minus minus; static Divide divide; static Multiply multiply; static Factorial factorial;

if("+" == operatorName) return plus;

if("-" == operatorName) return minus;

if("*" == operatorName) return multiply;

if("!" == operatorName) return factorial;

if("/" == operatorName) return divide; } code

And here's one that uses words like "plus" and "factorial" instead of "+" and "!": code format="cpp"
 * FullyNamedMathOperatorFactory**
 * 1) include "FullyNamedMathOperatorFactory.h"


 * 1) include "Plus.h"
 * 2) include "Minus.h"
 * 3) include "Multiply.h"
 * 4) include "Divide.h"
 * 5) include "Factorial.h"

FullyNamedMathOperatorFactory::FullyNamedMathOperatorFactory(void) { nameToOperator["plus"] = new Plus; nameToOperator["minus"] = new Minus; nameToOperator["divide"] = new Divide; nameToOperator["multiply"] = new Multiply; nameToOperator["factorial"] = new Factorial; }

FullyNamedMathOperatorFactory::~FullyNamedMathOperatorFactory(void) { for(MapType::iterator iter = nameToOperator.begin; iter != nameToOperator.end; ++iter) delete (*iter).second; }

MathOperator &FullyNamedMathOperatorFactory::getOperatorNamed(const std::string &operatorName) { MathOperator *mathOperator = nameToOperator[operatorName]; return *mathOperator; }

code <--Back