Template_Method

4704 ワード

#include <iostream>



using namespace std;

#define DESTROY_POINTER(ptr) if (ptr) { delete ptr; ptr = NULL; }













class TemplateMethod

{

public:

    void AlgorithmA() { Step1(); Step2(); Step3(); }

    void AlgorithmB() { Step3(); Step2(); Step1(); }

    

protected:

    virtual void Step1()=0;

    virtual void Step2()=0;

    virtual void Step3()=0;

};





class ConcreteTemplateA : public TemplateMethod

{

public:

    ConcreteTemplateA() {}

    ~ConcreteTemplateA() {}



protected:

    void Step1() { cout<<"ConcreteTemplateA::Step1"<<endl; }

    void Step2() { cout<<"ConcreteTemplateA::Step2"<<endl; }

    void Step3() { cout<<"ConcreteTemplateA::Step3"<<endl; }

};





class ConcreteTemplateB : public TemplateMethod

{

public:

    ConcreteTemplateB() {}

    ~ConcreteTemplateB() {}



protected:

    void Step1() { cout<<"ConcreteTemplateB::Step1"<<endl; }

    void Step2() { cout<<"ConcreteTemplateB::Step2"<<endl; }

    void Step3() { cout<<"ConcreteTemplateB::Step3"<<endl; }

};













int main(int argc, char *argv[])

{

    TemplateMethod* pTemplate = NULL;

    



    pTemplate = new ConcreteTemplateA;

    pTemplate->AlgorithmA();

    DESTROY_POINTER(pTemplate);

    

    pTemplate = new ConcreteTemplateB;

    pTemplate->AlgorithmB();

    DESTROY_POINTER(pTemplate);

    



    return 0;

}