Ở phần trước chúng ta đã nghiên cứu về nhóm design pattern “Cấu trúc”
Hôm nay chúng ta tiếp tục với nhóm design pattern mang tên “Hành vi” (Behavioral Patterns)
1. Định nghĩa
Nhóm design pattern theo “Hành vi” mà một nhóm tập trung vào việc phân chia nhiệm vụ giữa các đối tượng với nhau.
Nhóm “Cấu trúc” thì tập trung vào việc giao tiếp trong đối tương. Nhưng nhóm “Hành vi” lại tập trung vào việc giao tiếp ngoài đối tượng với nhau.
1.1 Stategy (chiến lược)
Định nghĩa một tập hợp các phương thức để có thể thay đổi linh hoạt dựa trên điều kiện hiện tại của tính huống.
vd: trên đoạn đường từ A -> B bạn phải đi từ A -> A’ = xe buýt, sau đó từ A’-> B= tàu. Bạn đã thay đổi chiến lược trên đường đi
public interface IGo { void Go(); } public BusGo : IGo { void Go() { Console.WriteLine("Go by Bus"); } } public TrainGo: IGo { void Go() { Console.WriteLine("Go by Train"); } } public class GoStategy { private IGo _go; public GoStategy(IGo go) { _go = go; } public SwitchVehicle(IGo vehicle) { _go = vehicle; } public void Go() { _go.Go(); } } // Using in main.cs GoStategy gogo = new GoStategy(new BusGo()); gogo.Go(); gogo.SwitchVehicle(new TrainGo()); gogo.Go();
1.2 Observer (người quan sát)
Duy trì một trạng thái thông nhất bằng cách quan sát những thay đổi trong danh sách đăng ký.
Vd: Đẩy thông báo tới những user đã Subcrible hệ thống
// chứa danh sách các subcriber. Khi Subcrible sẽ thêm người vào danh sách và ngược lại sẽ xóa ra. MessagePublisher publisher = new MessagePublisher(); // Create subscribers UserSubscriber alice = new UserSubscriber("Alice"); UserSubscriber bob = new UserSubscriber("Bob"); // Subscribe users to receive updates publisher.Subscribe(alice); publisher.Subscribe(bob); // Post a message - all subscribers get notified publisher.PostMessage("Hello, World!"); // Unsubscribe a user publisher.Unsubscribe(bob); // Post another message - only subscribed users get notified publisher.PostMessage("Second message");
1.3 Command (mệnh lệnh)
Là một CommandManager có nhiệm vụ lưu trữ các mệnh lệnh đã được thực thi của 1 đối tượng. Ví dụ undo/redo một đối tượng Document();
Document document = new Document(); CommandManager commandManager = new CommandManager(); // Simulate text editing commandManager.ExecuteCommand(new InsertTextCommand(document, "Hello, ", 0)); commandManager.ExecuteCommand(new InsertTextCommand(document, "World!", 7)); Console.WriteLine(document); // Output: Hello, World! // Undo last insert commandManager.Undo(); Console.WriteLine(document); // Output: Hello, // Redo last insert commandManager.Redo(); Console.WriteLine(document); // Output: Hello, World!
1.4 State (trạng thái)
Là một StateManager lưu giữ trạng thái của đối tượng. Vd: Normal, Enable, Disable textbox
// TextEditor chính là 1 StateManager chịu trách nhiệm thay đổi và lưu giữ trạng thái của đối tượng TextEditor editor = new TextEditor(); // Typing in normal state Console.WriteLine(editor.TypeText("This is normal text.")); // Change state to bold editor.SetState(new BoldTextState()); Console.WriteLine(editor.TypeText("This is bold text.")); // Change state to italic editor.SetState(new ItalicTextState()); Console.WriteLine(editor.TypeText("This is italic text."));
1.5 Template Method (phương thức mẫu)
Đóng vai trò như 1 khung sườn để thực thi một bài toán nào đó. Trì hoãn một vài bước để các lớp con tự định nghĩa logic của chính nó.
Phù hợp khi có 1 vài step chung và 1 vài step core cần lớp con tự định nghĩa
public abstract class DataProcessor { // The template method public void ProcessData() { var data = ReadData(); var processedData = ProcessDataCore(data); SaveData(processedData); } protected virtual string ReadData() { // Generic implementation, can be overridden Console.WriteLine("Reading generic data..."); return "Sample data"; } protected abstract string ProcessDataCore(string data); // Các lớp con sẽ phải định nghĩa xử lý riêng của mình protected virtual void SaveData(string data) { // Default implementation for saving data Console.WriteLine($"Saving data: {data}"); } } // Sử dụng trong main.cs DataProcessor csvProcessor = new CsvDataProcessor(); csvProcessor.ProcessData(); DataProcessor jsonProcessor = new JsonDataProcessor(); jsonProcessor.ProcessData();