Behavioral mode - template method mode (TEMPLATE METHOD)

1. Intent

Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method enables subclasses to redefine some specific steps of an algorithm without changing the structure of the algorithm.

2. Structure

Template Method Pattern

3. The difference between template mode and strategy mode

Strategy pattern: defines a set of algorithms, encapsulates each algorithm, and makes them interchangeable. The key point is that each algorithm is process-integrated and independent.
Template method mode: Templates define the skeleton, such as the steps or sequence of execution. Parts of the skeleton are implemented in the parent class, while the personalized behavior of the subclass is implemented by the subclass inheritance.
The essence of the difference is that the strategy pattern replaces the entire process. The template mode replaces some specific content in the fixed process.

4. Examples

//template.h
#pragma once
#include <iostream>

class Template
{
public:
    virtual ~Template() = default;

    virtual void operate1() = 0;
    virtual void operate2() = 0;

    void method()
    {
        operate1();
        operate2();
    }
};

class Concrete1 : public Template
{
public:
    void operate1() { std::cout << "Concrete1 operate1\n"; }
    void operate2() { std::cout << "Concrete1 operate2\n"; }

};

class Concrete2 : public Template
{
public:
    void operate1()    { std::cout << "Concrete2 operate1\n"; }
    void operate2() { std::cout << "Concrete2 operate2\n"; }

};

//main.cpp
#include <memory>
#include "template.h"

int main(int argc, char* argv[]) {
    std::shared_ptr<Template> tmplt_ptr = std::make_shared<Concrete1>();
    tmplt_ptr->method();

    tmplt_ptr = std::make_shared<Concrete2>();
    tmplt_ptr->method();

    return 0;
}

5. Example 2

class DPGamesFramework
{
protected:
    virtual bool loadingGame();
    virtual bool startGame();
    virtual bool playingGame();
    virtual bool endGame();
public:
    virtual void Run() final;
    virtual ~DPGamesFramework();
private:
    void errorLog(std::string funcName);
};

void DPGamesFramework::Run() 
{
    if (!loadingGame())
    {
        errorLog("loadingGame");
        return;
    }
    if (!startGame())
    {
        errorLog("startGame");
        return;
    }
    if (!playingGame())
    {
        errorLog("playingGame");
        return;
    }
    if (!endGame())
    {
        errorLog("endGame");
        return;
    }
}

class DPCjGame : public DPGamesFramework
{
public:
    bool loadingGame();
    bool startGame();
    bool playingGame();
    bool endGame();
};
int main()
{
    DPGamesFramework* cjGame = new DPCjGame();
    cjGame->Run();
    return 0;
}

Guess you like

Origin blog.csdn.net/rukawashan/article/details/124574414