템플릿 메서드 패턴
객체지향과 디자인 패턴(최범균 저) 템플릿 메서드 패턴 정리한 내용입니다.
상황
문제
해결방법
// 추상 메소드가 존재하는 상위 클래스를 정의한다.
public abstract class Author {
public Auth authenticate(String id, String pw) {
if(!doAuthenticate(id, pw)) throw createException();
return createAuth(id);
}
protected abstract boolean doAuthenticate(String id, String pw);
protected abstract Auth createAuth(String id);
}
// 상위 클래스를 상속 받아 추상 메소드만 오버라이드 한다.
public class LdapAutor extends Author {
@Override
protected boolean doAuthenticate(String id, String pw) {
return ldapClient.authenticate(id, pw);
}
@Override
protected Auth createAuth(String id) {
LdapContext ctx = ldapClient.find(id);
return new Auth(id, ctx.getAttributes("name"));
}
}
// 사용자는 특정 구현체를 선택하여 로직을 수행한다.
public static void main(String[] args) {
Author author = new LdapAutor();
author.authenticate("incheol", "password");
}템플릿 메서드와 전략 패턴의 조합
Last updated