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

การปรับโครงสร้างโค้ดด้วยรูปแบบการออกแบบ

เรียนรู้การปรับโครงสร้างฐานโค้ดเดิมอย่างเป็นระบบ โดยใช้รูปแบบการออกแบบที่เหมาะสมเพื่อปรับปรุงโครงสร้างและความสามารถในการบำรุงรักษา

การปรับโครงสร้างโค้ดด้วยรูปแบบการออกแบบ เป็นบทเรียน 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 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Refactoring with Design Patterns

What is refactoring? It's about improving existing code's structure without changing its external behavior. Why bring design patterns into it? Patterns offer proven, reusable solutions to common design problems, making your refactoring more systematic and effective. This leads to clearer, more maintainable, and extensible code.

Spotting Code Smells

Before you refactor, you need to know what to refactor. Code smells are indicators that something might be wrong in your code's design. They aren't bugs, but they can lead to them or make code harder to change.

  • Long Method: A method that does too much.
  • Large Class: A class with too many responsibilities.
  • Duplicate Code: The same code logic appearing in multiple places.
  • Conditional Complexity: Too many if/else or switch statements.

Systematic Refactoring Steps

Refactoring should be a disciplined process, not a rushed rewrite. Here’s a simple workflow:

  1. Identify a Code Smell: Find an area in your code that could be improved.
  2. Choose a Design Pattern: Select a pattern that addresses the identified smell.
  3. Apply the Pattern: Make small, incremental changes, ensuring tests pass at each step.
  4. Test Thoroughly: Verify that the external behavior remains unchanged.

Remember: "Red, Green, Refactor" is a powerful mantra!

Strategy for Conditional Logic

Let's tackle a common smell: methods with extensive conditional logic (many if/else or switch statements). This makes code hard to read, test, and extend. The Strategy Pattern helps by encapsulating varying behaviors into separate, interchangeable objects.

Consider a basic calculator:

public class SimpleCalculator {
  public int calculate(String operation, int a, int b) {
    if ("add".equals(operation)) {
      return a + b;
    } else if ("subtract".equals(operation)) {
      return a - b;
    } else if ("multiply".equals(operation)) {
      return a * b;
    }
    throw new IllegalArgumentException("Unknown operation");
  }

  public static void main(String[] args) {
    SimpleCalculator calc = new SimpleCalculator();
    System.out.println("Add: " + calc.calculate("add", 5, 3));
    System.out.println("Subtract: " + calc.calculate("subtract", 5, 3));
  }
}

Refactoring to Strategy

To refactor the calculator, we'll introduce an Operation interface and specific strategy classes for each operation. The Calculator then uses an instance of an Operation strategy. This makes it easy to add new operations without modifying the Calculator class.

interface Operation {
  int execute(int a, int b);
}

class AddOperation implements Operation {
  @Override
  public int execute(int a, int b) {
    return a + b;
  }
}

class SubtractOperation implements Operation {
  @Override
  public int execute(int a, int b) {
    return a - b;
  }
}

public class RefactoredCalculator {
  private Operation operation;

  public void setOperation(Operation operation) {
    this.operation = operation;
  }

  public int calculate(int a, int b) {
    if (operation == null) {
      throw new IllegalStateException("Operation not set");
    }
    return operation.execute(a, b);
  }

  public static void main(String[] args) {
    RefactoredCalculator calc = new RefactoredCalculator();
    
    calc.setOperation(new AddOperation());
    System.out.println("Add: " + calc.calculate(5, 3));
    
    calc.setOperation(new SubtractOperation());
    System.out.println("Subtract: " + calc.calculate(5, 3));
  }
}

State Pattern for Behavior Changes

Another common code smell is an object whose behavior changes based on its internal state, often managed by many if/else or switch statements within its methods. The State Pattern allows an object to alter its behavior when its internal state changes, making it appear as if the object changed its class.

Let's look at a traffic light:

public class SimpleTrafficLight {
  private String currentState;

  public SimpleTrafficLight() {
    this.currentState = "RED"; // Initial state
  }

  public void change() {
    if ("RED".equals(currentState)) {
      currentState = "GREEN";
      System.out.println("Traffic light is now GREEN.");
    } else if ("GREEN".equals(currentState)) {
      currentState = "YELLOW";
      System.out.println("Traffic light is now YELLOW.");
    } else if ("YELLOW".equals(currentState)) {
      currentState = "RED";
      System.out.println("Traffic light is now RED.");
    }
  }

  public static void main(String[] args) {
    SimpleTrafficLight light = new SimpleTrafficLight();
    light.change(); // GREEN
    light.change(); // YELLOW
    light.change(); // RED
  }
}

Refactoring to State

With the State pattern, we'll define an interface for the traffic light's state (TrafficLightState) and concrete classes for each state (RedState, GreenState, YellowState). The TrafficLight class will hold a reference to its current state object and delegate behavior to it. This cleanly separates state-specific behavior.

interface TrafficLightState {
  void change(TrafficLight context);
}

class RedState implements TrafficLightState {
  @Override
  public void change(TrafficLight context) {
    System.out.println("Traffic light is now GREEN.");
    context.setState(new GreenState());
  }
}

class GreenState implements TrafficLightState {
  @Override
  public void change(TrafficLight context) {
    System.out.println("Traffic light is now YELLOW.");
    context.setState(new YellowState());
  }
}

class YellowState implements TrafficLightState {
  @Override
  public void change(TrafficLight context) {
    System.out.println("Traffic light is now RED.");
    context.setState(new RedState());
  }
}

public class TrafficLight {
  private TrafficLightState currentState;

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

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

  public void change() {
    currentState.change(this);
  }

  public static void main(String[] args) {
    TrafficLight light = new TrafficLight();
    light.change(); // GREEN
    light.change(); // YELLOW
    light.change(); // RED
  }
}

Selecting the Right Pattern

Deciding which pattern to apply can be challenging. Here are some common smells and suitable patterns:

  • Conditional Complexity (if/else, switch): Often refactored with Strategy, State, or Command.
  • Duplicate Code: Can often be solved by Factory Method, Template Method, or extracting common logic into a superclass.
  • Tight Coupling: Facade, Mediator, Observer can reduce dependencies.
  • Incompatible Interfaces: Adapter pattern is perfect for this.
  • Adding Functionality Dynamically: Decorator pattern.

Why Refactor with Patterns?

Systematically applying design patterns during refactoring provides significant advantages:

  • Improved Readability: Patterns give a common vocabulary and structure.
  • Enhanced Maintainability: Changes are localized and easier to implement.
  • Increased Extensibility: New features can often be added without modifying existing code (Open/Closed Principle).
  • Better Testability: Decoupled components are easier to unit test.

It transforms messy code into a well-structured, robust system.

Refactoring Quiz

Imagine you have a class that handles various report generation formats (PDF, CSV, XML) using a large switch statement. You want to make it easy to add new formats without changing the core report generator class.

Recap: Refactor with Patterns

Today, we learned how to approach refactoring systematically using design patterns. We explored common code smells and saw how patterns like Strategy and State can transform complex conditional logic into cleaner, more extensible designs.

Remember, refactoring is an ongoing process that, when guided by design patterns, significantly improves your codebase's quality and adaptability.

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

บทเรียน “การปรับโครงสร้างโค้ดด้วยรูปแบบการออกแบบ” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “การปรับโครงสร้างโค้ดด้วยรูปแบบการออกแบบ”

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

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

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

บทเรียน “การปรับโครงสร้างโค้ดด้วยรูปแบบการออกแบบ” ใช้เวลานานแค่ไหน

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

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

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

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

  1. เจาะลึกการกลับทิศทางการพึ่งพา
  2. การแยกอินเทอร์เฟซในทางปฏิบัติ
  3. การปรับโครงสร้างโค้ดด้วยรูปแบบการออกแบบ
  4. ความเชี่ยวชาญด้านความรับผิดชอบเดียวและการเปิดรับการขยาย
← กลับไปที่ Clean Architecture & Design Patterns in Practice