본문 바로가기
Spring/DesighPattern

GOF패턴-Template Method(행동)

by windy7271 2023. 2. 21.
728x90
반응형

temlate(템플릿) 란 모양자 

 

알고리즘의 구조를 메소드의 정의하고 하위 클래스에서 알고리즘의 구조의 변경없이 알고리즘을 재정의 하는 패턴

 알고리즘이 단계별로 나누어 지거나, 같은 역할을 하는 메소드이지만 여러곳에서 다른형태로 사용이 필요한 경우 유용한 패턴이다.

 

언제 쓰냐?

- 구현하려는 알고리즘이 일정한 프로세스가 있다.

- 구현하려는 알고리즘의 변경 가능성일 클 때

 

사용 방법?

- 알고리즘을 여러단계로 나눈다

- 나눠진 알고리즘을 메소드로 선언한다

- 알고리즘 수행할 템플릿 메소드를 만든다.

- 하위 클래스에서 나눠진 메소드들을 구현한다.

 

다이어그램

 

 

템플릿 메소드

package Template;

public abstract class AbstGameConnectHelper{
    protected abstract String doSecurity(String str);
    protected abstract boolean authentication(String id, String password);
    protected abstract int authorization(String username);
    protected abstract String connection(String info);

//    노출이 되면 안됨 >> private 을 붙이는것은 안됨 이유 하우클래스가 재정의 해야함
//    protected 외부에서는 호출 못하지만 하위클래스에서 사용할 수 있다.


    // 템플릿 메소드
    public String requestConnection(String encodedInfo){
        //보안 -> 암호화 된 문자열을 복호화

        String decodedInfo = doSecurity(encodedInfo);

        String id = "AAA";
        String password = "BBB";

        // 인증 과정
        if (!authentication(id,password)){
            throw new Error("로그인 실패");
        }

        // 권한
        String username = "";
        int i = authorization(username);
        if(i==0){
            System.out.println("game manager");
        } else if (i == 1) {
            System.out.println("유료");
        } else if (i == -1) {
            throw new Error("Shut Down");
        } else{
            System.out.println("무");
        }
        return connection(decodedInfo);

    }
}

 

하위 메소드

package Template;

//하위 메소드
public class DefaultGameConnectionHelper extends AbstGameConnectHelper{
    @Override
    protected String doSecurity(String string) {

        System.out.println("디코드");
        return string;
    }

    @Override
    protected boolean authentication(String id, String password) {
        System.out.println("확인");
        return true;
    }

    @Override
    protected int authorization(String username) {
        System.out.println("10시이후 권한 확인");
        return 0;
    }

    @Override
    protected String connection(String info) {
        System.out.println("마지막 접속 단계");
        return info;
    }
}

 

package Template;

public class Main {
    public static void main(String[] args) {

        AbstGameConnectHelper helper = new DefaultGameConnectionHelper();
        helper.requestConnection("접속정보");


    }
}

 

 

클라이언트가 요청하면 템플릿메소드를 거쳐 하위 메소드에 들어가 들고 오는것이다

 

  • 장점
    • 중복된 코드를 없애고 SubClass 에서는 비즈니스 로직에만 집중할 수 있음 (SRP)
    • 나중에 새로운 비즈니스 로직이 추가되어도 기존 코드를 수정하지 않아도 됨 (OCP)
  • 단점
    • 클래스 파일을 계속 만들어야 함
    • 자식 클래스는 실제로 부모 클래스를 사용하지 않는데 단순히 패턴 구현을 위한 상속 때문에 의존 관계를 갖고 있음

 

출처: https://bcp0109.tistory.com/369

반응형

댓글