Template Method Pattern: defines the skeleton of an algorithm in a method, and delays some steps into subclasses. The template method allows subclasses to redefine some of the steps in the algorithm without altering the algorithm structure.
Hollywood principles: Low-level components must never invoke a high-layer component, and high-level components control when and how to involve lower-layer components. The Hollywood principles teach us a trick to create a resilient design.
#ifndef Caffeinebeverage_h#defineCaffeinebeverage_h#include<iostream>using namespacestd;classcaffeinebeverage{ Public: voidPreparerecipe () {boilwater (); Brew (); Pourincup (); if(Customerwantscondiments ()) {addcondiments (); } } Virtual voidBrew () =0; Virtual voidAddcondiments () =0; voidBoilwater () {cout<<"Boiling Water"<<Endl; } voidPourincup () {cout<<"pouring into Cup"<<Endl; } //You can use policy mode optimizations for hooks. Virtual BOOLcustomerwantscondiments () {return true; }};#endifCaffeinebeverage
#ifndef tea_h#defineTea_h#include"CaffeineBeverage.h"#include<iostream>using namespacestd;classTea: Publiccaffeinebeverage{ Public: voidBrew () {cout<<"steeping the tea"<<Endl; } voidaddcondiments () {cout<<"Adding Lemon"<<Endl; }};#endifTea
#ifndef Coffee_h#defineCoffee_h#include"CaffeineBeverage.h"#include<iostream>#include<string>using namespacestd;classCoffee: Publiccaffeinebeverage{ Public: voidBrew () {cout<<"Dripping Coffee through filter"<<Endl; } voidaddcondiments () {cout<<"Adding Sugar and Milk"<<Endl; } BOOLcustomerwantscondiments () {stringAnswer =string(""); cout<<"would milk and sugar with your coffee (y/n)?"<<Endl; CIN>>answer; if(Answer = =string("y")) { return true; } Else { return false; } }};#endifCoffee
#include"CaffeineBeverage.h"#include"Coffee.h"#include"Tea.h"intMain () {Tea* Tea =NewTea; Tea-Preparerecipe (); Coffee* Coffee =NewCoffee; Coffee-Preparerecipe (); return 0;}main.cpp
Template method Mode