템플릿 메서드 패턴
작업 순서는 기반 클래스에 고정하고 일부 단계를 하위 클래스가 구현하는 행위 패턴.
· 마지막 업데이트: 2026-11-05 · 9 min read
개요
보고서를 만드는 절차가 양쪽 공백 제거 → 빈 문자열 검사 → 형식 변환의 세 단계로 고정돼 있는 상황을 보자. 출력 형식마다 이 세 단계를 매번 복사해 넣다 보면 어느 한 클래스에서 빈 값 검사를 빼먹거나 순서가 뒤집히기 쉬울 뿐 아니라, 형식이 늘어날 때마다 똑같은 앞단 코드를 되풀이해 적어야 한다.
해법은 간단하다. 앞단의 공백 정리와 빈 값 검사는 부모 기반 클래스에 한 번만 적어 두고, 형식마다 달라지는 마지막 변환 단계만 하위 클래스로 넘기면 된다. 이처럼 알고리즘의 전체 뼈대(순서)를 부모 메서드 하나에 못 박아 두고 달라지는 단계만 하위 클래스가 채우게 만드는 설계가 템플릿 메서드(Template Method) 패턴이다.
UML
위 UML에서 ReportTemplate.Run()은 입력 정리와 검증을 마친 뒤에야 추상 메서드인 Format()을 부른다. 하위 클래스인 UpperReport와 JsonReport는 오직 Format() 하나만 구현할 뿐, 전체 순서를 쥐고 있는 Run()은 건드리지 않는다.
역사
1994년 GoF의 Design Patterns는 알고리즘의 뼈대를 유지한 채 일부 단계만 하위 클래스가 재정의하게 하는 이 구조를 행위(Behavioral) 패턴인 Template Method로 정리했다.1
왜 사용하는가?
이곳저곳에 흩어져 있던 실행 순서가 Run() 한곳에 모인다. 덕분에 전체 흐름이 한눈에 읽히고 각 하위 클래스는 자기 출력 포맷을 빚는 데만 집중할 수 있으며, 특히 C#에서 Run()을 비가상(non-virtual) 메서드로 막아 두면 하위 클래스가 단계 순서를 임의로 뒤바꾸지 못해 새 출력 형식은 Format()만 채워 넣으면 끝난다.
다만 변하는 단계를 상속(override)으로 푸는 구조이다 보니, 이미 만들어진 객체의 변환 규칙을 실행 도중에 다른 것으로 갈아끼우기는 어렵다. 바로 이 지점에서 처리 규칙을 별도 객체나 함수로 주입하는 전략(Strategy) 패턴과 길이 갈린다.
예제
양쪽 공백을 걷어낸 다음, 대문자 형식의 보고서로 만든다.
using System;
using System.Collections.Generic;
using System.Linq;
ExportResult result = new UpperReport().Run(" hello ");
Console.WriteLine(result.Success + ": " + result.Text);
sealed record ExportResult(bool Success, string Text);
// 반복되는 순서와 검사 규칙은 기반 클래스 한곳에서 관리한다.
abstract class ReportTemplate
{
public ExportResult Run(string input)
{
string value = input.Trim();
if (value.Length == 0) return new ExportResult(false, "EMPTY_INPUT");
return new ExportResult(true, "REPORT|" + Format(value));
}
protected abstract string Format(string value);
}
// 하위 클래스는 공통 흐름 전체가 아니라 이 변환 단계만 바꾼다.
sealed class UpperReport : ReportTemplate
{
protected override string Format(string value) => value.ToUpperInvariant();
}
sealed class JsonReport : ReportTemplate
{
protected override string Format(string value) => System.Text.Json.JsonSerializer.Serialize(value);
}
True: REPORT|HELLORun()이 정리 → 검사 → 변환의 세 박자를 틀어쥐고 있기 때문에, 대문자 변환만 적어 넣은 UpperReport든 다른 하위 클래스든 모두 똑같은 앞단 검증을 거치게 된다.
확장 예제
이번에는 JSON 형식 구현을 쓰고, 빈 입력도 함께 넘겨 본다. 빈 값은 Format()에 닿기 전에 실패 결과로 돌아온다. 형식이 바뀌어도 순서는 그대로다.
using System;
using System.Collections.Generic;
using System.Linq;
ReportTemplate report = new JsonReport();
foreach (string input in new[] { " hello ", " " })
{
ExportResult result = report.Run(input);
Console.WriteLine(result.Success + ": " + result.Text);
}
sealed record ExportResult(bool Success, string Text);
// 반복되는 순서와 검사 규칙은 기반 클래스 한곳에서 관리한다.
abstract class ReportTemplate
{
public ExportResult Run(string input)
{
string value = input.Trim();
if (value.Length == 0) return new ExportResult(false, "EMPTY_INPUT");
return new ExportResult(true, "REPORT|" + Format(value));
}
protected abstract string Format(string value);
}
// 하위 클래스는 공통 흐름 전체가 아니라 이 변환 단계만 바꾼다.
sealed class UpperReport : ReportTemplate
{
protected override string Format(string value) => value.ToUpperInvariant();
}
sealed class JsonReport : ReportTemplate
{
protected override string Format(string value) => System.Text.Json.JsonSerializer.Serialize(value);
}
True: REPORT|"hello"
False: EMPTY_INPUT성공 여부 불리언과 결과 문자열을 튜플로 나란히 돌려주므로 호출자는 빈 입력 실패와 정상 보고서를 헷갈리지 않고 가려낼 수 있다. 만약 여러 구현이 공유해야 할 고정된 앞뒤 절차가 애초에 없다면, 고작 함수 하나를 바꾸자고 상속 계층부터 세울 필요는 없다.
TypeScript 예제
앞선 C# 구조를 TypeScript로 그대로 옮긴 코드다. 공백 제거와 빈 문자열 검사, 머리말(REPORT: ) 붙이기까지는 부모 클래스의 run()이 한 번만 정의하고 형식별 문자열 변환만 추상 메서드 format()으로 빼내어, 검증 로직을 복사하다 빠뜨릴 위험 없이 변환 규칙만 갈아끼울 수 있게 했다.
type ExportResult = { success: true; text: string } | { success: false; code: "EMPTY_INPUT" };
// 반복되는 순서와 검사 규칙은 기반 클래스 한곳에서 관리한다.
abstract class ReportTemplate {
run(value: string): ExportResult {
const clean = value.trim();
if (clean.length === 0) return { success: false, code: "EMPTY_INPUT" };
return { success: true, text: "REPORT|" + this.format(clean) };
}
protected abstract format(value: string): string;
}
// 하위 클래스는 공통 흐름 전체가 아니라 이 변환 단계만 바꾼다.
class UpperReport extends ReportTemplate {
protected override format(value: string): string { return value.toUpperCase(); }
}
class JsonReport extends ReportTemplate {
protected override format(value: string): string { return JSON.stringify(value); }
}
for (const report of [new UpperReport(), new JsonReport()]) {
const result = report.run(" hello ");
console.log(result.success ? result.text : result.code);
}
const empty = new UpperReport().run(" ");
console.log(empty.success ? empty.text : empty.code);REPORT|HELLO
REPORT|"hello"
EMPTY_INPUTTypeScript에는 C#의 비가상 메서드에 해당하는 final 제한이 없으므로 여기서도 run()을 다시 정의하지 않고 format()만 구현한다. 빈 입력은 변환기를 부르기 전에 실패 결과로 빠진다. 비교에 쓴 입력은 ASCII이고, Unicode 공백과 대소문자 규칙은 두 런타임에서 다를 수 있다.
상속 대신 함수와 LINQ로 조합하기
달라지는 구멍이 문자열 변환 함수 딱 하나뿐이라면 굳이 하위 클래스를 여럿 만들지 않고 변환 함수를 인수로 직접 받는 쪽이 훨씬 가볍다. Run 함수가 공백 정리와 빈 값 검사를 그대로 책임지면서 호출자가 넘긴 변환 람다만 마지막에 불러 주는 식인데, LINQ의 Select와 맞물리면 앞선 상속 예제에서 하위 클래스 하나가 통째로 맡던 몫이 함수 인자 하나로 줄어든다.
C#
using System;
using System.Linq;
using System.Text.Json;
ExportResult Run(string input, Func<string, string> format)
{
string value = input.Trim();
if (value.Length == 0) return new ExportResult(false, "EMPTY_INPUT");
return new ExportResult(true, "REPORT|" + format(value));
}
var inputs = new[] { " hello ", " " };
// 형식만 전달하며, 빈 입력은 변환 함수를 호출하기 전에 실패한다.
var results = inputs.Select(input => Run(input, value => JsonSerializer.Serialize(value)))
.ToArray();
foreach (ExportResult result in results) Console.WriteLine(result.Text);
sealed record ExportResult(bool Success, string Text);TypeScript
type ExportResult = { success: true; text: string } | { success: false; code: "EMPTY_INPUT" };
function run(input: string, format: (value: string) => string): ExportResult {
const value = input.trim();
if (value.length === 0) return { success: false, code: "EMPTY_INPUT" };
return { success: true, text: "REPORT|" + format(value) };
}
const inputs = [" hello ", " "];
// 공통 흐름은 한 함수에 두고 각 입력에 적용한다.
const results = inputs.map(input => run(input, value => JSON.stringify(value)));
for (const result of results) console.log(result.success ? result.text : result.code);REPORT|"hello"
EMPTY_INPUT상속 기반의 Template Method에서는 하위 클래스가 부모의 실행 흐름과 protected 멤버에 단단히 묶인다. 변주할 지점(hook)과 하위 클래스가 계속 불어나는 상황이라면 사소한 변환 규칙 하나도 부모 클래스 변경에 휘둘리게 되므로, 그럴 때는 정리 → 검사 → 변환이라는 순서는 그대로 유지한 채 함수 전달이나 전략(Strategy) 패턴으로 풀어내는 편이 훨씬 유연하다.
Microsoft: Introduction to LINQ queries