模版方法模式

模版方法模式是指把不变的行为搬移到超类,去除子类中的重复代码的一种模式,它提供了很好的代码复用平台。

有时候遇到一系列相同步骤执行的过程(具体实现可能不同)时,可以考虑模版方法模式。把不变的行为搬移到单一的地方。

举例:

#include 
using namespace std;

class Paper
{
public:
    void Task1()
    {
        printf("Paper::task1\n");
        Answer1();
    }
    
    void Task2()
    {
        printf("Paper::task2\n");
        Answer2();
    }
    
    virtual void Answer1()
    {
        printf("Paper::Answer1\n");
    }
    
    virtual void Answer2()
    {
        printf("Paper::Answer2\n");
    }
};

class PaperA : public Paper
{
public:
    virtual void Answer1()
    {
        printf("PaperA::Answer1\n");
    }
    
    virtual void Answer2()
    {
        printf("PaperA::Answer2\n");
    }
};

class PaperB : public Paper
{
public:
    virtual void Answer1()
    {
        printf("PaperB::Answer1\n");
    }
    
    virtual void Answer2()
    {
        printf("PaperB::Answer2\n");
    }
};

int main()
{
    Paper* a = new PaperA();
    a->Task1();
    a->Task2();
    delete a;
    a = NULL;
    
    Paper* b = new PaperB();
    b->Task1();
    b->Task2();
    delete b;
    b = NULL;
    
    return 0;
}

你可能感兴趣的:(模版方法模式)