※父/子類別
public abstract class AbstractTemplate { protected abstract void method1(); protected abstract void method2(); protected abstract void method3(); public void templateMethod() { this.method1(); this.method2(); this.method3(); } } -------------------- public class Concrete1 extends AbstractTemplate { @Override protected void method1() { System.out.println("Concrete1 m1"); } @Override protected void method2() { System.out.println("Concrete1 m2"); } @Override protected void method3() { System.out.println("Concrete1 m3"); } } -------------------- public class Concrete2 extends AbstractTemplate { @Override protected void method1() { System.out.println("Concrete2 m1"); } @Override protected void method2() { System.out.println("Concrete2 m2"); } @Override protected void method3() { System.out.println("Concrete2 m3"); } }
※
※測試
AbstractTemplate c1 = new Concrete1(); AbstractTemplate c2 = new Concrete2(); c1.templateMethod(); System.out.println(); c2.templateMethod();
※結果:
Concrete1 m1
Concrete1 m2
Concrete1 m3
Concrete2 m1
Concrete2 m2
Concrete2 m3
沒有留言:
張貼留言