0Pricing
Clean Architecture & Design Patterns in Practice · 강의

템플릿 메서드와 상태 패턴

템플릿 메서드로 알고리즘의 뼈대를 정의하고 상태 패턴으로 객체가 동작을 변경하도록 만드는 방법을 배웁니다.

템플릿 메서드와 상태 패턴은(는) CoddyKit의 무료 Clean Architecture & Design Patterns in Practice 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Clean Architecture & Design Patterns in Practice 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Clean Architecture & Design Patterns in Practice 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Behavioral Patterns Focus

Welcome back! In this lesson, we'll dive into two powerful behavioral design patterns: the Template Method and the State patterns.

These patterns help manage algorithms and object behavior in flexible ways, making your code easier to extend and maintain.

What is Template Method?

The Template Method pattern defines the skeleton of an algorithm in an operation, deferring some steps to subclasses.

It lets subclasses redefine certain steps of an algorithm without changing the algorithm's overall structure.

Algorithm Skeleton

Imagine a recipe with fixed steps, but some ingredients or cooking times can vary. The core "how-to" is set, but details are flexible.

  • An abstract class defines the overall algorithm with a final "template method."
  • This method calls a series of primitive operations (abstract methods) that subclasses must implement.
  • It can also include concrete methods (shared steps) and hook methods (optional steps).

Template Method in Action

Let's consider making beverages. Both coffee and tea require boiling water and pouring into a cup. But brewing and adding condiments differ.

The Template Method allows us to define the common steps once, while allowing specific beverage classes to customize their unique steps.

Beverage Maker Example

Here's how we can implement a generic BeverageMaker using the Template Method. Notice the prepareBeverage() method is final, fixing the algorithm.

public abstract class BeverageMaker {

  // The template method - defines the algorithm's skeleton
  public final void prepareBeverage() {
    boilWater();
    brew();
    pourInCup();
    addCondiments();
  }

  // Common steps
  private void boilWater() {
    System.out.println("Boiling water");
  }

  private void pourInCup() {
    System.out.println("Pouring into cup");
  }

  // Abstract steps - must be implemented by subclasses
  protected abstract void brew();
  protected abstract void addCondiments();
}

public class CoffeeMaker extends BeverageMaker {
  @Override
  protected void brew() {
    System.out.println("Dripping coffee through filter");
  }

  @Override
  protected void addCondiments() {
    System.out.println("Adding sugar and milk");
  }
}

public class TeaMaker extends BeverageMaker {
  @Override
  protected void brew() {
    System.out.println("Steeping the tea bag");
  }

  @Override
  protected void addCondiments() {
    System.out.println("Adding lemon");
  }
}

public class Main {
  public static void main(String[] args) {
    System.out.println("--- Making Coffee ---");
    BeverageMaker coffee = new CoffeeMaker();
    coffee.prepareBeverage();

    System.out.println("\n--- Making Tea ---");
    BeverageMaker tea = new TeaMaker();
    tea.prepareBeverage();
  }
}

What is the State Pattern?

The State pattern allows an object to alter its behavior when its internal state changes. It appears as if the object has changed its class.

Instead of using many if/else or switch statements, you encapsulate each state's behavior into a separate class.

Context and States

Think of a traffic light. Its behavior (what light is active) changes based on its current state (Red, Yellow, Green).

  • The Context class holds a reference to a State object and delegates state-specific behavior to it.
  • The State Interface declares methods for state-specific behaviors.
  • Concrete State classes implement the State Interface, providing behavior for a particular state.

Traffic Light States

A TrafficLight object doesn't have complex logic itself. Instead, it holds a reference to its current LightState (e.g., RedLightState, GreenLightState).

When an event occurs (like a timer tick), the TrafficLight delegates the action to its current LightState object, which then handles the transition to the next state.

Traffic Light Simulation

Here’s a simple traffic light simulation using the State pattern. The TrafficLight context changes its internal LightState object, which dictates its behavior.

// State Interface
interface LightState {
  void handleRequest(TrafficLight light);
  String getStateName();
}

// Concrete State: Red Light
class RedLightState implements LightState {
  @Override
  public void handleRequest(TrafficLight light) {
    System.out.println("Red light: STOP!");
    light.setState(new GreenLightState()); // Transition to Green
  }

  @Override
  public String getStateName() {
    return "Red";
  }
}

// Concrete State: Green Light
class GreenLightState implements LightState {
  @Override
  public void handleRequest(TrafficLight light) {
    System.out.println("Green light: GO!");
    light.setState(new YellowLightState()); // Transition to Yellow
  }

  @Override
  public String getStateName() {
    return "Green";
  }
}

// Concrete State: Yellow Light
class YellowLightState implements LightState {
  @Override
  public void handleRequest(TrafficLight light) {
    System.out.println("Yellow light: CAUTION!");
    light.setState(new RedLightState()); // Transition to Red
  }

  @Override
  public String getStateName() {
    return "Yellow";
  }
}

// Context
class TrafficLight {
  private LightState currentState;

  public TrafficLight() {
    // Initial state
    this.currentState = new RedLightState();
  }

  public void setState(LightState state) {
    this.currentState = state;
  }

  public void change() {
    System.out.print("Current state: " + currentState.getStateName() + " -> ");
    currentState.handleRequest(this);
  }
}

public class Main {
  public static void main(String[] args) {
    TrafficLight light = new TrafficLight();

    // Simulate light changes
    light.change(); // Red -> Green
    light.change(); // Green -> Yellow
    light.change(); // Yellow -> Red
    light.change(); // Red -> Green
  }
}

Pattern Identification

You are designing a document processing system where different document types (PDF, DOCX, TXT) share a common conversion process to HTML, but each has unique steps for parsing its content.

Which design pattern would best suit defining the overall conversion process while allowing specific parsing steps to vary?

Summary of Patterns

Great job! You've learned about two powerful behavioral patterns:

  • The Template Method pattern allows you to define a fixed algorithm structure while letting subclasses implement specific steps.
  • The State Pattern enables an object to change its behavior based on its internal state, encapsulating state-specific logic into separate classes.

These patterns boost flexibility and maintainability in your designs!

자주 묻는 질문

“템플릿 메서드와 상태 패턴” 강의는 무료인가요?

네 — “템플릿 메서드와 상태 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Clean Architecture & Design Patterns in Practice 강의 전체를 잠금 해제할 수 있습니다. Clean Architecture & Design Patterns in Practice 강의에는 총 4개의 강의가 포함되어 있습니다.

“템플릿 메서드와 상태 패턴”에서 뭘 배우나요?

템플릿 메서드로 알고리즘의 뼈대를 정의하고 상태 패턴으로 객체가 동작을 변경하도록 만드는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Clean Architecture & Design Patterns in Practice을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Clean Architecture & Design Patterns in Practice을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Clean Architecture & Design Patterns in Practice은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“템플릿 메서드와 상태 패턴” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Clean Architecture & Design Patterns in Practice 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Clean Architecture & Design Patterns in Practice 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 옵서버와 전략 패턴
  2. 커맨드와 이터레이터 패턴
  3. 템플릿 메서드와 상태 패턴
  4. Mediator와 Chain of Responsibility
← Clean Architecture & Design Patterns in Practice(으)로 돌아가기