Menu
Coddy logo textTech

템플릿 메서드 패턴

Coddy Python 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 64개 중 52번째.

템플릿 메서드 패턴은 기본 클래스에서 알고리즘의 뼈대를 정의하고, 서브클래스가 알고리즘의 구조를 변경하지 않고 특정 단계를 재정의할 수 있도록 합니다.

다음은 템플릿 메서드를 포함한 기본 클래스입니다:

class DataProcessor:
    def process(self):
        """알고리즘 구조를 정의하는 템플릿 메서드"""
        self.read_data()
        self.process_data()
        self.save_data()
    
    def read_data(self):
        print("Reading data...")
    
    def process_data(self):
        raise NotImplementedError("Subclasses must implement this")
    
    def save_data(self):
        print("Saving data...")

템플릿 메서드 process()는 알고리즘 단계를 정의하고, process_data()는 서브클래스가 구현하도록 남겨 둡니다.

추상 메서드를 구현하는 구체적인 클래스를 만드세요:

class CSVProcessor(DataProcessor):
    def process_data(self):
        print("Processing CSV data")

class JSONProcessor(DataProcessor):
    def process_data(self):
        print("Processing JSON data")

각 구체 클래스는 필요한 단계를 자체적으로 구현합니다.

템플릿 메서드를 사용하세요:

csv_processor = CSVProcessor()
csv_processor.process()

print()  # 빈 줄

json_processor = JSONProcessor()
json_processor.process()

게임 템플릿을 사용하여 또 다른 예제를 만들어 보세요:

class Game:
    def play(self):
        """게임을 플레이하기 위한 템플릿 메서드"""
        self.start_game()
        self.play_game()
        self.end_game()
    
    def start_game(self):
        print("Game started!")
    
    def play_game(self):
        raise NotImplementedError("Define the game rules")
    
    def end_game(self):
        print("Game ended!")

class Chess(Game):
    def play_game(self):
        print("Playing chess - thinking strategically...")

class Soccer(Game):
    def play_game(self):
        print("Playing soccer - running and kicking...")

chess = Chess()
chess.play()

출력:

Reading data...
Processing CSV data
Saving data...

Reading data...
Processing JSON data
Saving data...
Game started!
Playing chess - thinking strategically...
Game ended!

핵심 요점: 템플릿 메서드 패턴은 부모 클래스에서 공통 알고리즘 구조를 정의하는 동시에, 자식 클래스가 특정 단계를 사용자 지정할 수 있도록 합니다. 부모 클래스는 전체 흐름을 제어하지만, 자식 클래스는 구체적인 구현을 제공합니다. 이를 통해 일관된 구조를 유지하면서도 개별 단계에서 유연성을 확보할 수 있습니다.

challenge icon

챌린지

중급

template.py에 템플릿 메서드 패턴을 구현하세요. 추상 Report 클래스는 템플릿 메서드 generate()를 소유하며, 항상 동일한 세 단계를 동일한 순서로 실행합니다: header(), body(), footer().

  • header()는 모든 리포트에서 공유되며 === Report ===를 출력합니다.
  • body()는 추상 메서드입니다. 각 서브클래스가 자체 콘텐츠를 출력합니다.
  • footer()는 기본값이 === End ===인 훅이며, 서브클래스에서 재정의할 수 있습니다.

그런 다음 두 개의 구체적인 리포트를 작성하세요.

  • SalesReport(total)은 총합을 self._total에 저장하고 본문에서 Total sales: {total}을 출력합니다.
  • InventoryReport(items)는 목록을 self._items에 저장하고, 본문에서 각 항목마다 Item: {item}을 출력하며, 푸터를 재정의하여 === {count} items ===를 출력합니다.

driver.py는 잠겨 있습니다. 이 파일은 리포트를 생성하고 리포트에서 generate()를 호출합니다. 서브클래스 간에 다른 것은 단계의 구현뿐이며, 단계의 순서는 기본 클래스에 한 번만 정의되어 있습니다.

직접 해보기

from template import SalesReport, InventoryReport

# 테스트 케이스 핸들러 (변경하지 마세요)
test_case = input()

if test_case == "sales_test":
    SalesReport(1500).generate()
elif test_case == "inventory_test":
    InventoryReport(["Laptop", "Mouse"]).generate()
elif test_case == "both_test":
    for report in [SalesReport(200), InventoryReport(["Pen"])]:
        report.generate()
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Python 컴파일러