Understanding Template method pattern

谁说我不能喝 提交于 2019-12-19 10:08:24

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/22015933/understanding-template-method-pattern

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