ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Design Pattern] Template Method Pattern
    Learn/Architecture 2022. 8. 28. 10:19

    # 개요

    프레임워크를 구성하는데 사용되는 패턴으로 특별한게 아니고 개발하면서 늘 하던 자연스러운 패턴

     

    공통적인 부분은 상위 클래스에 구현

    •   상위 클래스에 concrete method로 구현 (final을 붙여서 override를 막을 수 있음) --> Encapsulation
    •   하위 클래스마다 달라질 수 있는 부분은 abstract method로 구현

    예시

    • 공통적인 부분은 prepareRecipe에 모아서 구현 (template method pattern)
    • 음료 종류에 따라 공통적인 부분만 여기에 정의
    • 음료에 따라 달라지는 부분은 하위 클래스에 구현
    public abstract class CaffeineBeverage {
    	final void prepareRecipe() {
    		boilWater();
    		brew();
    		pourInCup();
    		addCondiments();
    	}
    
    	abstract void brew();
    	abstract void addCondiments();
    	
    	public void boilWater() {
    		System.out.println("Boiling water");
    	}
    
    	public void pourInCup() {
    		System.out.println("Pouring into cup");
    	}
    }

     

    # Hook Method

    상위  클래스에 정의되었으나, 하위 클래스가 override로 operation에 개입할 수 있게 한 것

     

    예시

    prepareRecipe를 아래와 같이 구현하면 하위 클래스에서 costumerWantsCondiments를 override해서 addCondiments의 실행 여부를 결정할 수 있다. 

    public abstract class CaffeineBeverage {
    	final void prepareRecipe() {
    		boilWater();
    		brew();
    		pourInCup();
    		if (customerWantsCondiments()) addCondiments();
    	}
        
    	abstract void brew();
    	abstract void addCondiments();
        
    	public void boilWater() {
    		Sysetm.out.println("Boiling water"); 
    	}
        
    	public void pourInCup() {
    		System.out.println("Pouring into cup");
    	}
        
    	boolean customerWantsCondiments() {
    		return true;
    	}
    }

     

    # Hollywoord Principle

    • 배우에게 "니가 먼저 전화하지마라. 우리가 필요하면 전화걸겠다." 라고 하는 것에 빗대어 표현
      (Don't call us, we'll call you!")
    • 상위 컴포넌트가 하위 컴포넌트에 의존하면 잘못되었다는 법칙

     

    # QUIZ

    Q1. Template Method 패턴은 class scope의 패턴인가? 아니면 object scope의 패턴인가?

    A. class scope의 패턴이다. inheritance만으로 구현 가능하므로 object까지 필요는 없다. 

     

    Q2. Template Method 패턴과 Strategy 패턴 모두 알고리즘의 다양성을 높이는데 활용될 수 있는데, 어떤 차이가 있는가?

    Strategy Pattern : 알고리즘 자체를 바꿔주는 방식

    Template Pattern: 알고리즘의 특정 부분을 바꾸는 방식

     

     

     

     

     

     

     

     

     

     

     

     

    'Learn > Architecture' 카테고리의 다른 글

    [Design Pattern] State Pattern  (0) 2022.08.29
    [Design Pattern] Iteration Pattern  (0) 2022.08.28
    [Design Pattern] Observer Pattern  (0) 2022.08.27
    [Design Pattern] Strategy Pattern  (0) 2022.08.26
    [Design Pattern] GRASP Principle  (0) 2022.08.24

    댓글

Designed by Tistory.