Template Method (1)

 Creational Patterns ( 생성 패턴 )

These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 

생성패턴은 객체의 생성로직을 숨기고 new 명령어를 통하지 않고 객체를 생성하는 방법들을 제공한다. 이는 특정 상황에서 어떤 방법으로 객체를 생성해야할지를 결정하는데 있어서 유연성을 제공한다. 


 Structural Patterns ( 구조적 패턴 )

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 

구조적 패턴들은 클래스와 객체의 구성에 관여한다.

 

 Behavioral Patterns ( 행위적 패턴 )

These design patterns are specifically concerned with communication between objects.

이 패턴들은 객체들 사이의 커뮤니케이션에 관심을 가진다.

 

오늘 살펴볼 Template Method 패턴은 Behavioral 패턴에 속한다.  

 

템 플릿하면 뭐가 떠오르는가? 사전적 의미는 형판, 견본이다. 우리가 일상적으로 쓸 때 템플릿이라 하면 뭔가의 기본구조(?)라고 생각을 할 수 있을 것이다. 이 템플릿 메소드는 바로 그런 형판, 견본, 기본구조의 역할을 하는 메소드이다. 그리고 이런 메소드를 이용하는 패턴을 템플릿 메소드 패턴이라고 이해하면 된다. 자 아래 그림을 살펴보자.

 


 

 

위 그림은 소방관, 목수, 우체부, 관리자 등 다양한 직업의 사람들을 객체로 만들었다. 이 사람들은 공통적으로 일하는 사람들이므로 Worker라는 클래스의 하위로 만들었고 모든 사람들은 동일한 일과 순서가 있다. 이 일과 순서는 DailyRoutine()내에 정의되어있고 Worker 클래스를 이용하는 클라이언트에서는 DailyRoutine()만 호출한다. 그러면 이 Worker가 소방관이냐, 우체부냐에 따라 work()에서 하는 일이 달라진다. 위 그림에서보면 모든 사람들이 work()를 오버라이드해서 재정의하고있기 때문이다. 여기서 DailyRoutine() 메소드가 템플릿 메소드가 되는 것이고 이런 식의 패턴을 템플릿 메소드 패턴이라 하는 것이다. 

 

Template Method Pattern Structure

 


 


패턴의 목적 ( Intent ) :
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.


어떤 작업을 수행하는 알고리즘의 뼈대를 정의하고 과정은 하위클래스가 정의하게끔 한다. 템플릿 메소드는 하위클래스들이 알고리즘의 구조에 변화를 주지 않는 선에서 알고리즘 내의 특정 과정만 재정의 할 수 있게끔 해준다.

 

패턴이 나오게 된 동기 ( Motivation ) :



 워 드 프로세서를 예를들어 설명하자면 Document(문서)파일과 Application(워드프로세서)가 있는데 이 워드프로세서가 문서를 열어본다는 시나리오를 생각해보자. OpenDocument()는 문서가 열수 있는 문서인지(읽어들일 수 있는지) 검사를 할 것이고, 워드프로세서내에서 정의한 Document객체를 생성하고 파일로부터 문서를 읽어들여 객체에 저장할 것이다.  

We call OpenDocument a template method. A template method defines an algorithm in terms of abstract operations that subclasses override to provide concrete behavior. Application subclasses define the steps of the algorithm that check if the document can be opened (CanOpenDocument) and that create the Document (DoCreateDocument). Document classes define the step that reads the document (DoRead). The template method also defines an operation that lets Application subclasses know when the document is about to be opened (AboutToOpenDocument), in case they care.  

By defining some of the steps of an algorithm using abstract operations, the template method fixes their ordering, but it lets Application and Document subclasses vary those steps to suit their needs.

 

여기서 이 OpenDocument()는 하나의 템플릿 메소드이다. 템플릿 메소드는 말그대로 특정 동작을 하기위한 골격만 제공한다. 골격내부의 구성은 하위클래스들이 하도록 하는 것이다. 

 

 

유용성 ( Applicability ) :

The Template Method pattern should be used

· to implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.

템플릿 메소드 패턴은 변하지 않을 알고리즘의 구조만 정의하고 구체적인 구현은 하위클래스들에게 위임하고자 할 때 사용한다. 

 

· when common behavior among subclasses should be factored and localized in a common class to avoid code duplication. This is a good example of"refactoring to generalize" as described by Opdyke and Johnson.

You first identify the differences in the existing code and then separate the differences into new operations. Finally, you replace the differing code with a template method that calls one of these new operations.

템플릿 메소드 패턴은 여러 하위 클래스들 중에서 중복된 부분을 제거하기 위해서도 사용될 수 있다.


· to control subclasses extensions. You can define a template method that calls "hook" operations (see Consequences) at specific points, thereby permitting extensions only at those points.

템플릿 메소드 패턴은 하위 클래스들의 확장을 컨트롤하고자 할 때 이용할 수도 있다. 우리는 템플릿 메소드에 특정시점에 hook를 호출하도록 정의하여 그 특정 시점에만 확장을 허용하도록 할 수도 있다. ( 무슨 말인지 모르겠다. 아래쪽에 Consequences에서 hook가 뭔지 더 알아보자 ) 

 

 

등장 인물 ( Participants ) :
· AbstractClass (Application)
o defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm.
o implements a template method defining the skeleton of an algorithm.The template method calls primitive operations as well as operationsdefined in AbstractClass or those of other objects.
· ConcreteClass (MyApplication)
o implements the primitive operations to carry out subclass-specific steps of the algorithm.

 

원리 ( Collaborations ) :

ConcreteClass relies on AbstractClass to implement the invariant steps of the algorithm.


패턴 사용의 장단점 ( Consequences ): 

Template methods are a fundamental technique for code reuse. They are particularly important in class libraries, because they are the means for factoring out common behavior in library classes.
Template methods lead to an inverted control structure that's sometimes referred to as "the Hollywood principle," that is, "Don't call us, we'll call you" .
This refers to how a parent class calls the operations of a subclass and not the other way around.

Template methods call the following kinds of operations:
· concrete operations (either on the ConcreteClass or onclient classes);
· concrete AbstractClass operations (i.e., operations that are generally useful to subclasses);
· primitive operations (i.e., abstract operations);
· factory methods (see Factory Method); and
· hook operations, which provide default behavior that subclasses can extend if necessary. A hook operation often doesnothing by default. It's important for template methods to specify which operations arehooks (may be overridden) and which are abstract operations(must be  overridden). To reuse an abstract class effectively,subclass writers must understand which operations are designed foroverriding.
A subclass can extend a parent class operation's behavior byoverriding the operation and calling the parent operation explicitly:


void DerivedClass::Operation () {
// DerivedClass extended behavior
ParentClass::Operation();
}

 

Unfortunately, it's easy to forget to call the inherited operation.We can transform such an operation into a template method to give the parent control over how subclasses extend it. The idea is to call a hook operation from a template method in the parent class.Then subclasses can then override this hook operation:


void ParentClass::Operation () {
// ParentClass behavior
HookOperation();
}


HookOperation does nothing in ParentClass:


void ParentClass::HookOperation () { }


Subclasses override HookOperation to extend its behavior:


void DerivedClass::HookOperation () {
// derived class extension
}


관련 패턴들 : 

Factory Methods are often called by template methods. In the Motivation example, the factory method DoCreateDocument is called by the template method OpenDocument.
Strategy : Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.

 

추가 정보 :     

  • Strategy is like Template Method except in its granularity.
  • Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm.
  • Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class.
  • Factory Method is a specialization of Template Method.

 

 

 

출처 : http://sourcemaking.com/design_patterns/template_method

         Design Patterns : Element of Reusable Object Oriented Software ( by GoF, 1994 )