设计模式之Template Method

1、设计模式的使用场景

模板方法模式(Template Method) 
解释一下模板方法模式,就是指:一个抽象类中,有一个主方法,再定义1…n个方法,可以是抽象的,也可以是实际的方法,定义一个类,继承该抽象类,重写抽象方法,通过调用抽象类,实现对子类的调用,先看个关系图:

左为结构化软件设计流程,右为面向对象结构化设计流程

class LIbrary{     
public:
    //稳定 template method
    void Run()
    {
        Step1();
        if (Step2())
        {
            Step3();
        }
        for (int i = 0; i < 4; i++)
        {
            Step4();
        }
        Step5();
    }
    virtual ~LIbrary(){}
protected:
    void Step1() //稳定
    {
        //....
    }
    void Step3() //稳定
    {
        //....
    }
    void Step5() //稳定
    {
        //....
    }
    virtual bool Step2() = 0;
    virtual bool Step4() = 0;
};

class Application : public LIbrary{
protected:
    virtual bool Step2(){
        //子类重写实现
    }
    virtual bool Step4(){
        //子类重写实现
    }
};

int main()
{
    LIbrary* pLib = new Application();
    pLib->Run();
    delete pLib;
}

转载于:https://www.cnblogs.com/zhuifeng-mayi/p/11054443.html

猜你喜欢

转载自blog.csdn.net/weixin_33722405/article/details/93646606