TEMPLATE METHOD (Class Behavioral)
[color=red]Purpose[/color]
Identifies the framework of an algorithm, allowing implementing
classes to define the actual behavior.
[color=red]Use When[/color]
1 A single abstract implementation of an algorithm is needed.
2 Common behavior among subclasses should be localized to a
common class.
3 Parent classes should be able to uniformly invoke behavior in
their subclasses.
4 Most or all subclasses need to implement the behavior.
[color=red]Example[/color]
A parent class, InstantMessage, will likely have all the methods
required to handle sending a message. However, the actual
serialization of the data to send may vary depending on the
implementation. A video message and a plain text message
will require different algorithms in order to serialize the data
correctly. Subclasses of InstantMessage can provide their
own implementation of the serialization method, allowing the
parent class to work with them without understanding their
implementation details.
[color=red]Purpose[/color]
Identifies the framework of an algorithm, allowing implementing
classes to define the actual behavior.
[color=red]Use When[/color]
1 A single abstract implementation of an algorithm is needed.
2 Common behavior among subclasses should be localized to a
common class.
3 Parent classes should be able to uniformly invoke behavior in
their subclasses.
4 Most or all subclasses need to implement the behavior.
[color=red]Example[/color]
A parent class, InstantMessage, will likely have all the methods
required to handle sending a message. However, the actual
serialization of the data to send may vary depending on the
implementation. A video message and a plain text message
will require different algorithms in order to serialize the data
correctly. Subclasses of InstantMessage can provide their
own implementation of the serialization method, allowing the
parent class to work with them without understanding their
implementation details.
package javaPattern.templateMethod;
abstract class AbstractClass{
public void templateMethod(){
subMethod1();
subMethod2();
}
public abstract void subMethod1();
public abstract void subMethod2();
}
class ConcreteClassA extends AbstractClass{
@Override
public void subMethod1() {
System.out.println("具体类A的方法1");
}
@Override
public void subMethod2() {
System.out.println("具体类A的方法2");
}
}
class ConcreteClassB extends AbstractClass{
@Override
public void subMethod1() {
System.out.println("具体类B的方法1");
}
@Override
public void subMethod2() {
System.out.println("具体类B的方法2");
}
}
public class TemplateMethod {
public static void main(String[] args) {
AbstractClass ac ;
ac = new ConcreteClassA();
ac.templateMethod();
ac = new ConcreteClassB();
ac.templateMethod();
}
}
本文介绍模板方法设计模式的目的及应用场景,通过实例演示如何在Java中实现该模式。父类定义算法骨架,允许子类定义具体行为。

被折叠的 条评论
为什么被折叠?



