Template_Method - shoonie/StudyingDesignPattern GitHub Wiki

Intent

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets you subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

Diagram

disgram

Consequences

  1. Template methods are a fundamental technique for code reuse.
  2. Template methods call the following kinds of operations:
  • concrete operations
  • concrete AbstractClass operations.
  • primitive operations.
  • factory methods.
  • hook operations. which provide default behavior that subclasses can extend if necessary.

Implementation

  1. Using C++ access control.
  2. Minimizing primitive operations.
  3. Naming conventions.

Sample Code

//https://www.robertlarsononline.com/2017/05/11/state-pattern-using-cplusplus/
#include <iostream>

class Pizza {
public:
	Pizza(std::string description);
	virtual ~Pizza();
	void Prepare();

protected:
	virtual void PrepareDough();
	virtual void AddSauce();
	virtual void AddToppings() = 0;
	virtual void Bake();

private:
	std::string m_description;
};

Pizza::Pizza(std::string description)
	: m_description(description) {
}

Pizza::~Pizza() {
}

void Pizza::Prepare()
{
	std::cout << "Preparing a " << m_description << "...\n";
	PrepareDough();
	AddSauce();
	AddToppings();
	Bake();
	std::cout << "\n";
}

void Pizza::PrepareDough()
{
	std::cout << "preparing dough\n";
}

void Pizza::AddSauce()
{
	std::cout << "adding sauce\n";
}

void Pizza::Bake()
{
	std::cout << "bake pizza\n";
}


class CheesePizza : public Pizza {
public:
	CheesePizza();
	virtual ~CheesePizza();

protected:
	virtual void AddToppings();
};

CheesePizza::CheesePizza()
	: Pizza(std::string("Cheese Pizza")) {
}

CheesePizza::~CheesePizza() {
}

void CheesePizza::AddToppings()
{
	std::cout << "adding cheese topping\n";
}

class MeatLoversPizza : public Pizza {
public:
	MeatLoversPizza();
	virtual ~MeatLoversPizza();

protected:
	virtual void AddToppings();
};

MeatLoversPizza::MeatLoversPizza()
	: Pizza(std::string("Meat Lover's Pizza")) {
}

MeatLoversPizza::~MeatLoversPizza() {
}


void MeatLoversPizza::AddToppings()
{
	std::cout << "adding cheese, pepperoni, sausage and bacon toppings\n";
}

int main()
{
	CheesePizza cheesePizza;
	cheesePizza.Prepare();
	MeatLoversPizza meatLoversPizza;
	meatLoversPizza.Prepare();
	return 0;
}
⚠️ **GitHub.com Fallback** ⚠️