0Pricing
Clean Architecture & Design Patterns in Practice · บทเรียน

รูปแบบ Template Method และ State

กำหนดโครงร่างอัลกอริทึมด้วย Template Method และเปิดให้ออบเจ็กต์เปลี่ยนพฤติกรรมด้วย State

รูปแบบ Template Method และ State เป็นบทเรียน Clean Architecture & Design Patterns in Practice ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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!

คำถามที่พบบ่อย

บทเรียน “รูปแบบ Template Method และ State” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “รูปแบบ Template Method และ State” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Clean Architecture & Design Patterns in Practice ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Clean Architecture & Design Patterns in Practice มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “รูปแบบ Template Method และ State”

กำหนดโครงร่างอัลกอริทึมด้วย Template Method และเปิดให้ออบเจ็กต์เปลี่ยนพฤติกรรมด้วย State คุณปฏิบัติ Clean Architecture & Design Patterns in Practice ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Clean Architecture & Design Patterns in Practice หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Clean Architecture & Design Patterns in Practice บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “รูปแบบ Template Method และ State” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Clean Architecture & Design Patterns in Practice นี้ได้ไหม

ได้ บทเรียน Clean Architecture & Design Patterns in Practice ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. รูปแบบ Observer และ Strategy
  2. รูปแบบ Command และ Iterator
  3. รูปแบบ Template Method และ State
  4. Mediator และ Chain of Responsibility
← กลับไปที่ Clean Architecture & Design Patterns in Practice