Design Patterns Explained C++ Code Examples – Chapter 9: The Stategy Pattern


Example 9-1: Implementing the Strategy Pattern

TOC

TaxController

TOP
TaxController.h

#pragma once
#include "CalcTax.h"

class TaskController
{
public:
    TaskController(void);
    void process();
    CalcTax *getTaxRulesForCountry();
public:
    ~TaskController(void);
};

TaxController.cpp

#include "TaskController.h"
#include "SalesOrder.h"
#include "CalcTax.h"
#include "USTax.h"

TaskController::TaskController(void)
{
}

TaskController::~TaskController(void)
{
}

void TaskController::process ()
{
    // this code is an emulation of a 
    // processing task controller
    // . . .
    // figure out which country you are in
    CalcTax *myTax;
    myTax= getTaxRulesForCountry();
    SalesOrder *mySO= new SalesOrder();
    mySO->process( myTax);
}

CalcTax *TaskController::getTaxRulesForCountry() 
{
    // In real life, get the tax rules based on
    // country you are in.  You may have the
    // logic here or you may have it in a
    // configuration file
    // Here, just return a USTax so this 
    // will compile.
    return new USTax;
}

SalesOrder

TOP

SalesOrder.h

#pragma once
#include "CalcTax.h"

class SalesOrder
{
public:
    SalesOrder(void);
    void process (CalcTax *TaxToUse);
public:
    ~SalesOrder(void);
};

SalesOrder.cpp

#include "SalesOrder.h"

SalesOrder::SalesOrder(void)
{
}

SalesOrder::~SalesOrder(void)
{
}

void SalesOrder::process (CalcTax *taxToUse)
{
    long itemNumber= 0;
    double price= 0;

    // given the tax object to use

    // . . .

    // calculate tax
    double tax= taxToUse->taxAmount( itemNumber, price);
}

CalcTax

TOP
CalcTax.h

#pragma once

class CalcTax
{
public:
    CalcTax(void);
    double virtual taxAmount( long, double)= 0;
public:
    ~CalcTax(void);
};

CalcTax.cpp

#include "CalcTax.h"

CalcTax::CalcTax(void)
{
}

CalcTax::~CalcTax(void)
{
}

CanTax

TOP
CanTax.h

#pragma once
#include "calctax.h"

class CanTax :
    public CalcTax
{
public:
    CanTax(void);
    double taxAmount( long, double);
public:
    ~CanTax(void);
};

CanTax.cpp

#include "CanTax.h"

CanTax::CanTax(void)
{
}

CanTax::~CanTax(void)
{
}

double CanTax::taxAmount (long itemSold, double price) 
{
    // in real life, figure out tax according to
    // the rules in Canada and return it
    // here, return 0 so this will compile
    return 0.0;
}

USTax

TOP
USTax.h

#pragma once
#include "calctax.h"

class USTax :
    public CalcTax
{
public:
    USTax(void);
    double taxAmount( long, double);

public:
    ~USTax(void);
};

USTax.cpp

#include "USTax.h"

USTax::USTax(void)
{
}

USTax::~USTax(void)
{
}

double USTax::taxAmount (long itemSold, double price) 
{
    // in real life, figure out tax according to
    // the rules in the US and return it
    // here, return 0 so this will compile
    return 0.0;
}