Understanding Template method pattern

2019-02-19 14:43发布

From what I understand, Template method is nothing but ordinary method that calls virtual or abstract methods defined in child class. Am I right, or is there something else important about this pattern that I miss?

abstract class Foo {
  public void IamTemplateMethod() { // which will be called in child class object
    method1(); // because this...
    method2(); // ...or this method was called in me
  }
  public virtual void method1() { ... } // to be overriden in child class
  public abstract void method2() { ... } // to be defined in child class
}

If I am right, are there any other common ways to implement Template method?

2条回答
2楼-- · 2019-02-19 15:23

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

查看更多
欢心
3楼-- · 2019-02-19 15:38

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.

查看更多
登录 后发表回答