Hướng dẫn Strategy Pattern với ví dụ đơn giản

Hướng dẫn Strategy Pattern với ví dụ đơn giản

Strategy pattern thuộc nhóm mẫu hành vi(behavioural pattern), nó được dùng để quản lý các thuật toán, mối liên quan giữa các object với nhau.

Khái niệm: Strategy pattern là một họ các thuật toán được gói gọn trong 1 object và dễ dàng thay đổi linh hoạt các thuật toán bên trong object.




Lược đồ Strategy pattern - diagram definition of the Strategy pattern

Theo lược đồ trên thì Context được tạo bởi Strategy. Phần Context có thể có bất cứ thứ gì khi nó yêu cầu thay đổi hành vi. Strategy đơn giản là interface, vì thế chúng ta có thể hoán đổi các thuật toán ConreteStrategy mà không ảnh hưởng tới Context.



Lược đồ hoạt động Strategy Pattern

Dùng Context từ client có nhiều hướng dùng, client có thể gọi Context, sau đó Context tự quyết định việc xử lý tiếp theo thay cho client. Tốt hơn là để nguyên quyết định này của Context, vì nó loại bỏ các câu lệnh chuyển đổi kiểu mà chúng ta đã thấy trong Factory pattern như hình dưới.


Khi nào dùng mẫu strategy pattern này:

Strategy pattern được dùng khi bạn muốn chọn thuật toán để chạy lúc runtime. Dùng tốt cho việc lưu file ở các định dạng khác nhau, chạy nhiều loại thuật toán sắp xếp, hay nén file.

Ví dụ Strategy pattern (java) về công cụ nén file (file compression tool) để tạo ra file .zip hay .rar

Đầu tiên ta cần strategy:
//Strategy Interface
public interface CompressionStrategy {
  public void compressFiles(ArrayList<File> files);
}
Sau đó ta cung cấp 2 implementation cho zip và rar
public class ZipCompressionStrategy implements CompressionStrategy {
  public void compressFiles(ArrayList<File> files) {
    //using ZIP approach
  }
}
public class RarCompressionStrategy implements CompressionStrategy {
  public void compressFiles(ArrayList<File> files) {
    //using RAR approach
  }
}
Đối tượng context sẽ cung cấp lựa chọn cho client để nén file. Nó như là thiết lập định dạng nén của phần mềm tương ứng với thuật toán nén sẽ được dùng. Chúng ta có thể thay đổi thuật toán từ lớp strategy khi dùng phương thức setCompressionStrategy trong Context.
public class CompressionContext {
  private CompressionStrategy strategy;
  //this can be set at runtime by the application preferences
  public void setCompressionStrategy(CompressionStrategy strategy) {
    this.strategy = strategy;
  }
  
  //use the strategy
  public void createArchive(ArrayList<File> files) {
    strategy.compressFiles(files);
  }
}
Các client có thể nén file theo mong muốn với CompressionContext
public class Client {
  public static void main(String[] args) {
    CompressionContext ctx = new CompressionContext();
    //we could assume context is already set by preferences
    ctx.setCompressionStrategy(new ZipCompressionStrategy());
    //get a list of files...
    ctx.createArchive(fileList);
  }
}
Nguồn: dzone.com/articles/design-patterns-strategy


Comment