Understanding Template method pattern

天大地大妈咪最大 提交于 2019-12-01 10:58:09

Yes. Most patterns are nothing special, but just smart approaches that seems to suit certain situations well, but still using normal OO principles (inheritance, polymorphism, abstraction etc.).

What the template method is saying is that sometimes, you need to do some common logic, with some sub-class specific logic interleaved with it. So the specific logic that you want to leave for each sub-class is defined as an abstract / virtual method that is left for the concrete class to implement, while the common business logic goes around it.

If you want to make sure that the common logic is not overridden you can also mark the template method not to be overridden (with the final keyword in Java for example), so you ensure that the common code you want to be always executed is always enforced, while allowing the sub-class to override the bits you want it to.

Think of it like a document template. The headings, footer and common elements will be there fixed and always the same, and then the specific details of what the specific document is being used for fill the blanks in between.

Template pattern provide a common sequence following for all the children of that method. So Template Pattern defines a final method which tells the sequence of execution.

abstract class Foo {
    public void final initilialize(){
        method1();
        method2();
        method3();
    }
    public void method1(){...}
    public void method2(){...}
    public void method3(){...}
}

Now child classes can extend Foo class. And Reference can be created as :

Foo obj1=new child();

For more information look into http://www.tutorialspoint.com/design_pattern/template_pattern.htm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!