Thay thế Template Method Pattern bằng Functional Interface và Lambda trong Modern Java

Template Method Pattern định nghĩa khung của một thuật toán trong một phương thức, chuyển một số bước triển khai cụ thể cho lớp con. Phương pháp kế thừa lớp (inheritance) truyền thống này thường dẫn đến hệ thống phân cấp lớp sâu và khó kiểm thử độc lập.

Kiến trúc tổng quan của Template Method Pattern truyền thống:

Template Method Design Pattern Architecture

Template Method truyền thống

Thường dựa trên abstract class kế thừa:

abstract class DocumentParser {
    // Template method
    public final void parse() {
        openDocument();
        extractText();
        closeDocument();
    }
    
    protected abstract void extractText(); // Lớp con phải override
    
    private void openDocument() { System.out.println("Opening..."); }
    private void closeDocument() { System.out.println("Closing..."); }
}

Cách tiếp cận hiện đại với Functional Interface

Thay vì ép buộc kế thừa, ta có thể định nghĩa một lớp duy nhất nhận vào các hành vi (behavior) cụ thể dưới dạng các Lambda expressions hoặc Functional Interfaces:

import java.util.function.Consumer;

public class ModernDocumentParser {
    public void parse(Consumer<String> textExtractor) {
        openDocument();
        // Thực thi logic được truyền vào qua Lambda
        textExtractor.accept("Document Content");
        closeDocument();
    }

    private void openDocument() { System.out.println("Opening..."); }
    private void closeDocument() { System.out.println("Closing..."); }
}

// Cách sử dụng siêu gọn nhẹ:
public class Main {
    public static void main(String[] args) {
        ModernDocumentParser parser = new ModernDocumentParser();
        // Truyền trực tiếp hàm trích xuất text mà không cần tạo subclass
        parser.parse(content -> System.out.println("Extracting: " + content));
    }
}

Ưu điểm vượt trội: Giảm thiểu tối đa số lượng class phụ, tăng khả năng tái sử dụng (composition over inheritance) và giúp code cực kỳ linh hoạt.

Bình luận (0)

Đang tải bình luận...