Java Tutorial/Design Pattern/Template Pattern

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Demo code for Template pattern

abstract class ApplicationFramework {
  public ApplicationFramework() {
    templateMethod(); // Dangerous!
  }
  abstract void customize1();
  abstract void customize2();
  final void templateMethod() {
    for (int i = 0; i < 5; i++) {
      customize1();
      customize2();
    }
  }
}
class MyApp extends ApplicationFramework {
  void customize1() {
    System.out.print("Hello ");
  }
  void customize2() {
    System.out.println("World!");
  }
}
public class TemplateMethod {
  public static void main(String args[]) {
    MyApp app = new MyApp();
  }
}





Template pattern with abstract class

public class TestTemplate {
  public static void main(String args[]) {
    Car automotiveRobot = new Car("Automotive");
    Cooker cookieRobot = new Cooker("Cook");
    automotiveRobot.go();
    cookieRobot.go();
  }
}
class Cooker extends Machine {
  private String name;
  public Cooker(String n) {
    name = n;
  }
  public void getParts() {
    System.out.println("Getting a flour and sugar....");
  }
  public void assemble() {
    System.out.println("Baking a cookie....");
  }
  public void test() {
    System.out.println("Crunching a cookie....");
  }
  public String getName() {
    return name;
  }
}
class Car extends Machine {
  private String name;
  public Car(String n) {
    name = n;
  }
  public void getParts() {
    System.out.println("Getting a carburetor....");
  }
  public void assemble() {
    System.out.println("Installing the carburetor....");
  }
  public void test() {
    System.out.println("Revving the engine....");
  }
  public String getName() {
    return name;
  }
}
abstract class Machine {
  public final void go() {
    start();
    getParts();
    assemble();
    test();
    stop();
  }
  public void start() {
    System.out.println("Starting....");
  }
  public void getParts() {
    System.out.println("Getting parts....");
  }
  public void assemble() {
    System.out.println("Assembling....");
  }
  public void test() {
    System.out.println("Testing....");
  }
  public void stop() {
    System.out.println("Stopping....");
  }
}