Programming/디자인 패턴

Template Method Pattern

Albothyl 2019. 1. 24. 13:22

Template Method Pattern

- 추상클레스에서 전체 비지니스 로직이 템플릿 형태로 존재하고, 특정 디테일 메소드를 추상 메소드로 선언하여 상속받은 각 클레스에서 처리한다.

- 전체적인 로직은 비슷하지만, 일부 로직만 틀릴 경우에 사용한다.






public class SubtleMethod extends StealingMethod {

  @Override

  protected String pickTarget() {

    return "shop keeper";

  }


  @Override

  protected void confuseTarget(String target) {

    System.out.println("Approach the {} with tears running and hug him!", target);

  }


  @Override

  protected void stealTheItem(String target) {

    System.out.println("While in close contact grab the {}'s wallet.", target);

  }

}



public class HitAndRunMethod extends StealingMethod {

  @Override

  protected String pickTarget() {

    return "old goblin woman";

  }


  @Override

  protected void confuseTarget(String target) {

    System.out.println("Approach the {} from behind.", target);

  }


  @Override

  protected void stealTheItem(String target) {

    System.out.println("Grab the handbag and run away fast!");

  }

}



public abstract class StealingMethod {

  protected abstract String pickTarget();

  protected abstract void confuseTarget(String target);

  protected abstract void stealTheItem(String target);


  public void steal() {

    String target = pickTarget();

    System.out.println("The target has been chosen as {}.", target);

    confuseTarget(target);

    stealTheItem(target);

  }

}



public class HalflingThief {

  private StealingMethod method;


  public HalflingThief(StealingMethod method) {

    this.method = method;

  }


  public void steal() {

    method.steal();

  }


  public void changeMethod(StealingMethod method) {

    this.method = method;

  }

}



public class App {

  public static void main(String[] args) {

    HalflingThief thief = new HalflingThief(new HitAndRunMethod());

    thief.steal();

    thief.changeMethod(new SubtleMethod());

    thief.steal();

  }

}