我们将某些特定的逻辑处理编写为一个方法。其某些实现的操作由子类来实现
父类定义为抽象类 其中2个为抽象方法,意为由子类来实现
父类
public abstract class TemplateDesgin { public abstract void doAnything(); public abstract void doSomething(); public final void doTemplate(){ doAnything(); doSomething(); }}
子类
public class Test extends TemplateDesgin { @Override public void doAnything() { System.out.println("doAnything..."); } @Override public void doSomething() { System.out.println("doSomething..."); } public static void main(String[] args) { Test test = new Test(); test.doTemplate(); }}
例如编写程序的计数耗时
父类
public abstract class TimeCounter { public abstract void programe(); public final long timeCounterMethod(){ long startTime = System.currentTimeMillis(); programe(); long endTime = System.currentTimeMillis(); return (endTime-startTime); }}
public class Time extends TimeCounter{ @Override public void programe() { for(int i=0;i<10000000;i++){ //System.out.print(i); } } public static void main(String[] args) { Time time = new Time(); System.out.println(time.timeCounterMethod()); }}