Chapter X - Template Method Pattern

Template Method (TemplateMethod): skeleton algorithm defined in one operation, while deferring some steps to subclasses. Method template so that subclasses can not change the structure of the algorithm to a certain step of the algorithm redefine

image

Basic Code

#include<iostream>
#include<string>

using namespace std;

/*AbstractClass是抽象类,其实也就是一个抽象模板,定义并实现了一个模板方法。这个模板方法一般是一个具体方法,
  他给出了一个顶级逻辑的骨架,而逻辑的组成步骤在相应的抽象操作中,推迟到子类实现。顶级逻辑也有可能调用一些具体方法。*/

class AbstractClass
{
public:
    virtual void PrimitiveOperation1() = 0;    //一些抽象行为,放到子类去实现
    virtual void PrimitiveOperation2() = 0;

    void TemplateMethod()    //模板方法,给出了逻辑的骨架,而逻辑的组成是一些相应的抽象操作,他们都推迟到子类实现
    {
        PrimitiveOperation1();
        PrimitiveOperation2();
    }
};

/*ConcreteClass,实现父类所定义的一个或多个抽象方法*/
class ConcreteClassA : public AbstractClass
{
public:
    void PrimitiveOperation1()
    {
        cout << "具体类A方法1实现" << endl;
    }

    void PrimitiveOperation2()
    {
        cout << "具体类A方法2实现" << endl;
    }
};

class ConcreteClassB : public AbstractClass
{
public:
    void PrimitiveOperation1()
    {
        cout << "具体类B方法1实现" << endl;
    }

    void PrimitiveOperation2()
    {
        cout << "具体类B方法2实现" << endl;
    }
};

int main()
{
    AbstractClass *c;
    c = new ConcreteClassA();
    c->TemplateMethod();

    c = new ConcreteClassB();
    c->TemplateMethod;

    system("pause");
    return 0;
}

Template method is to reflect its advantage through the move to change the behavior of the superclass, subclass remove duplicate code. Template Method pattern is to provide a good platform code reuse. When the variable and constant behavior of the method implemented in a subclass mixed together, the same behavior will be repeated in the subclass. We put these actions into a single place to move through the template method pattern, thus helping to get rid of duplicate sub-class of entanglement is not deformed.

Guess you like

Origin www.cnblogs.com/wfcg165/p/12004612.html