Header Ads

[OOP] Mẫu Strategy


1. Mẫu thiết kế Strategy dùng để làm gì?

Mẫu thiết kế Strategy trong OOP được sử dụng để cung cấp một cách linh hoạt để thay đổi hành vi của một đối tượng trong quá trình chạy của chương trình. Nó cho phép bạn định nghĩa một tập hợp các thuật toán khác nhau và cho phép đối tượng thay đổi thuật toán được sử dụng bên trong nó tại thời điểm thực thi.

Ví dụ, giả sử bạn đang phát triển một chương trình xử lý ảnh. Bạn muốn cho phép người dùng chọn giữa các thuật toán khác nhau để chuyển đổi ảnh sang định dạng khác nhau, như JPEG, PNG hoặc GIF. Thay vì triển khai một phương thức xử lý ảnh cố định, bạn có thể triển khai mẫu thiết kế Strategy để tạo ra một giao diện chung cho các thuật toán chuyển đổi ảnh khác nhau, và đưa ra một số lớp cụ thể để triển khai các thuật toán cụ thể.

Với mẫu thiết kế Strategy, người dùng có thể dễ dàng chuyển đổi giữa các thuật toán khác nhau chỉ bằng cách đặt thuật toán phù hợp vào đối tượng của bạn. Điều này giúp cho chương trình của bạn trở nên linh hoạt và dễ bảo trì hơn.

2.Ví dụ trong Java

// Khai báo một interface cho Strategy
public interface SortingStrategy {
    void sort(int[] array);
}

// Triển khai các thuật toán sắp xếp khác nhau bằng cách
// cài đặt interface SortingStrategy
public class BubbleSort implements SortingStrategy {
    @Override
    public void sort(int[] array) {
        // Triển khai thuật toán sắp xếp nổi bọt ở đây
    }
}

public class InsertionSort implements SortingStrategy {
    @Override
    public void sort(int[] array) {
        // Triển khai thuật toán sắp xếp chèn ở đây
    }
}

public class QuickSort implements SortingStrategy {
    @Override
    public void sort(int[] array) {
        // Triển khai thuật toán sắp xếp nhanh ở đây
    }
}

// Khai báo đối tượng Context để sử dụng mẫu Strategy
public class SortContext {
    private SortingStrategy sortingStrategy;

    public SortContext(SortingStrategy sortingStrategy) {
        this.sortingStrategy = sortingStrategy;
    }

    public void setSortingStrategy(SortingStrategy sortingStrategy) {
        this.sortingStrategy = sortingStrategy;
    }

    public void sortArray(int[] array) {
        sortingStrategy.sort(array);
    }
}

// Sử dụng đối tượng SortContext để triển khai thuật toán sắp xếp
public class Main {
    public static void main(String[] args) {
        int[] array = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
        SortContext sortContext = new SortContext(new BubbleSort());
        sortContext.sortArray(array);

        // Thay đổi thuật toán sắp xếp bằng cách đặt một
        // SortingStrategy khác vào SortContext
        sortContext.setSortingStrategy(new QuickSort());
        sortContext.sortArray(array);
    }
}

Trong ví dụ này, chúng ta định nghĩa một interface SortingStrategy và triển khai nó bằng các lớp BubbleSort, InsertionSort và QuickSort để triển khai các thuật toán sắp xếp khác nhau. Chúng ta cũng định nghĩa một lớp SortContext để sử dụng các thuật toán này.

Trong hàm main(), chúng ta tạo một đối tượng SortContext với một thuật toán BubbleSort được sử dụng để sắp xếp một mảng các số nguyên. Sau đó, chúng ta thay đổi thuật toán sắp xếp bằng cách đặt một SortingStrategy khác vào SortContext, và sử dụng nó để sắp xếp lại mảng.

3. Một số bài tập

Here are some exercises related to the Strategy pattern in OOP:

3.1. Shopping Cart:

  • Create a shopping cart class that allows a user to add products to their cart and calculate the total cost of the products.
  • Implement the Strategy pattern to allow users to choose different payment methods, such as credit card, PayPal, or cash on delivery.

3.2. Sorting Algorithm:

  • Create a program that uses different sorting algorithms to sort an array of integers, such as bubble sort, insertion sort, and quicksort.
  • Implement the Strategy pattern to allow the user to choose which sorting algorithm to use.

3.3. Game Character:

  • Create a game character class that has different attack behaviors, such as sword attack, bow attack, or magic attack.
  • Implement the Strategy pattern to allow the user to choose which attack behavior to use.

3.4. File Compression:

  • Create a program that compresses files using different compression algorithms, such as Huffman coding, LZW compression, or Run-length encoding.
  • Implement the Strategy pattern to allow the user to choose which compression algorithm to use.

3.5. Database Query:

  • Create a program that queries a database using different search algorithms, such as binary search or linear search.
  • Implement the Strategy pattern to allow the user to choose which search algorithm to use.

3.6. Image Editor:

  • Create an image editor program that allows the user to apply different filters, such as blur, grayscale, and sharpen.
    Implement the Strategy pattern to allow the user to choose which filter to apply.

3.7. Text Editor:

  • Create a text editor program that allows the user to format text in different ways, such as bold, italic, and underline.
  • Implement the Strategy pattern to allow the user to choose which formatting option to use.

3.8. Payment Gateway:

  • Create a payment gateway program that allows the user to pay using different methods, such as credit card, PayPal, and bank transfer.
  • Implement the Strategy pattern to allow the user to choose which payment method to use.

3.9. Game AI:

  • Create a game AI that has different behavior strategies, such as aggressive, defensive, and passive.
  • Implement the Strategy pattern to allow the AI to choose which behavior strategy to use.

3.10. Music Player:

  • Create a music player program that allows the user to play songs with different sound effects, such as echo, reverb, and chorus.
  • Implement the Strategy pattern to allow the user to choose which sound effect to use.

Không có nhận xét nào

Được tạo bởi Blogger.