DevEnjoy

One Step Closer

Template Method

Template Method 디자인 패턴

2015년 7월 7일 by YongPwi Leave a Comment
  • 변하지 않는 기능은 슈퍼클래스에 생성하고 자주 변경되며 확장할 기능은 서브클래스에 만든다.
  • 슈퍼클래스에 추상 메소드 또는 오버라이드 가능한 메소드를 정의
  • 코드의 기본 알고리즘을 담고 있는 템플릿 메소드 생성
  • 서브클래스에서 추상 메소드 구현 또는 훅 메소드 오버라이드하여 기능 확장
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
abstract class Work {
    // 1. 추상 메소드 또는 오버라이드 가능한 메소드를 정의
    public void workFlow() {
        stepOne();
        stepTwo();
        stepThr();
        stepFor();
    }
    // 2. 일반적인 구현은 기본 클래스에 정의
    protected void stepOne() { System.out.println( "Work.stepOne" ); }
    // 3. 변경 또는 기능확장이 필요한 메소드는 추상 메소드로 선언
    abstract protected void stepTwo();
    abstract protected void stepThr();
    protected void stepFor() { System.out.println( "Work.stepFor" ); }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
abstract class Teacher extends Work{
    // 4. 서브 클래스는 메소드 구현 또는 오버라이드하여 기능 확장
    // 1. 추상 메소드 또는 오버라이드 가능한 메소드를 정의
    protected void stepThr() {
        step3_1();
        step3_2();
        step3_3();
    }
    // 2. 일반적인 구현은 기본 클래스에 정의
    protected void step3_1() {
        System.out.println( "Teacher.step3_1" );
    }
    // 3. 변경 또는 기능확장이 필요한 메소드는 추상 메소드로 선언
    abstract protected void step3_2();
    protected void step3_3() {
        System.out.println( "Teacher.step3_3" );
    }
}
1
2
3
4
5
6
7
8
9
10
class MathTeacher extends Teacher {
    // 4. 서브 클래스는 메소드 구현 또는 오버라이드하여 기능 확장
    protected void stepTwo() { System.out.println( "MathTeacher   .stepTwo" ); }
    protected void step3_2() { System.out.println( "MathTeacher   .step3_2" ); }

    protected void stepFor() {
        System.out.println( "MathTeacher   .stepFor" );
        super.stepFor();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class TemplateMethodDemo {
   public static void main( String[] args ) {
       Work work = new MathTeacher();
       work.workFlow();
   }
}

// 결과
Work.stepOne
MathTeacher   .stepTwo
Teacher.step3_1
MathTeacher   .step3_2
Teacher.step3_3
MathTeacher   .stepFor
Work.stepFor
Posted in: Java, Programing Tagged: JAVA, Template Method, 디자인패턴

Calendar

6월 2025
일 월 화 수 목 금 토
« 4월    
1234567
891011121314
15161718192021
22232425262728
2930  

Recent Posts

  • ubuntu bastion 설정
  • Spring Boot properties 암호화
  • Git Repository Bitbucket과 Issue Tracker Redmine 연동 설정
  • Spring Security 동일 session 제어
  • Spring @Mock, @Mockbean, @InjectMock

Recent Comments

  • pzotov (Ubuntu 14.04에서 Sonarqube 6.7.1 service 등록)
  • cours de theatre paris (AWS ELB와 Auto Scaling 연동, nginx)
  • bayern munich (IntelliJ EAP Font rendering)
  • camiseta del chelsea (OS X에서 APP 아이콘 변경)
  • cheap football shirts replica (jQuery Ajax에서 json Array 직렬화)

Copyright © [the-year] [site-link].

Powered by [wp-link] and [theme-link].