템플릿 메소드(Template Method) 패턴

Lee InnJie·2022년 8월 31일
0

Design Pattern

목록 보기
21/22

Template Method Pattern

알고리즘의 구조를 템플릿으로 제공하는 방법. 각각의 내부 구현을 서브 클래스가 구현하도록 한다.
상속을 주로 사용한다.


Code Example

Client

public class Client {
  public static void amin(String[] args) {
    FileProcessor fileProcessor = new FileProcessor("number.txt");
    int reuslt = fileProcessor.process();
  }
}

FileProcessor

public class fileProcessor {
  private String path;
  public fileProcessor(String path) {
    this.path = path;
  }
  
  public int process() {
    try(BufferedReader reader = new BufferedReaderview(new FileReader(path))) {
      int result = 0;
      String line = null;
      while line = reader.readLine()) != null) {
        reuslt += Integer.parseInt(line);
      }
      return resuilt;
    }catch(IOexception e) {
      throw new IllegalArgumentExcpetion("path: + "aaa", e);
    }
  }
}

Code Example - 2

FileProcessor

public abstract class fileProcessor {
  private String path;
  public fileProcessor(String path) {
    this.path = path;
  }
  
  public int process() {
    try(BufferedReader reader = new BufferedReaderview(new FileReader(path))) {
      int result = 0;
      String line = null;
      while line = reader.readLine()) != null) {
        reuslt = getResult(result, Integer.parseInt(line));
      }
      
    }catch(IOexception e) {
      throw new IllegalArgumentExcpetion("path: + "aaa", e);
    }
  }
  protect abstract int getResult(int result, String line);
}

Plus

public class Plus extends FileProcessor {
  public Plus(String path) {
    super(path);
  }
  
  @Override
  protected int getResult(int result, int number) {
    return result += number;
  }
}

Template-Callback Pattern

콜백으로 상속 대신 위임을 사용하는 템플릿 패턴

Code Example 1-1

public interface Operator {
  abstract int getReuslt (int result, int number);
}

FileProcessor

public class fileProcessor {
  private String path;
  public fileProcessor(String path) {
    this.path = path;
  }
  
  public int process(Operator operator) {
    try(BufferedReader reader = new BufferedReaderview(new FileReader(path))) {
      int result = 0;
      String line = null;
      while line = reader.readLine()) != null) {
        reuslt = operator.getResult(result, Integer.parseInt(line));
      }
      
    }catch(IOexception e) {
      throw new IllegalArgumentExcpetion("path: + "aaa", e);
    }
  }
}

Client

public class Client {
  public static void main(String[] args) {
    FileProcessor fileProcessor = new FileProcesor("number.txt");
    int reuslt = fileProcessor.process(new Plus());
  }
}

장단점

장점

  • 템플릿 코드를 재사용하고 중복 코드를 줄일 수 있다.
  • 템플릿 코드를 변경하지 않고 상속을 받아서 구체적인 알고리즘만 변경할 수 있다.

단점

  • 리스코프 치환 원칙을 위반할 수도 있다.
  • 알고리즘 구도가 복잡할 수록 템플릿을 유지하기 어려워진다.

Example

HttpServlet

post, get -> 요청이 들어올 때 인스턴스 초기화

Configuration Adapter

내부 메소드들을 호출하고 구체화

JDBC Template

템플릿 콜백 패턴. execute를 사용해서 sql을 실행할 때 주로 insert 쿼리 시 사용된다.
get에는 query를 사용한다.

profile
⌒_⌒

0개의 댓글