Chain of Responsibility
Là một mẫu thiết kế giải quyết cho việc thực hiện 1 chuỗi các tác vụ có trình tự mà mỗi 1 tác vụ trong chuỗi đó được đảm nhiệm bởi 1 class.
abstract class Process { private Process _nextProcess; protected abstract void RunNext(); public void Run() { RunNext(); if(_nextProcess != null) { _nextProcess.Run(); } } public void SetNextProcess(Process process) { _nextProcess = process; } } class FirstProcess : Process { Protect override void RunNext() { System.Threading.Thread.Sleep(1000); } } class SecondProcess: Process { Protect override void RunNext() { System.Threading.Thread.Sleep(2000); } } class ThirdProcess: Process { Protect override void RunNext() { System.Threading.Thread.Sleep(3000); } } Process firstProcess = new FirstProcess(); Process secondProcess = new SecondProcess(); Process thirdProcess = new ThirdProcess(); firstProcess.SetNextProcess(secondProcess); secondProcess.SetNextProcess(thirdProcess); thirdProcess.SetNextProcess(null); firstProcess.Run();
Command Pattern :
Mẫu này dùng để lưu trữ lại các thao tác đối tượng như 1 history vậy. Ví dụ ta có 1 loạt action, khi ta muốn undo lại thì lục từ history ra mà xử lý.
//invoker class DocumentInvoker { private ArrayList _commands = new ArrayList(); private Document _doc = new Document(); public void Redo(int level) { Console.WriteLine("---- Redo {0} level", level); ((Command) _commands[level]).Redo(); } public void Undo(int level) { Console.WriteLine("---- Undo {0} level", level); ((Command) _commands[level]).Undo(); } public void Write(string text) { DocumentEditCommand cmd = new DocumentEditCommand(_doc, text); _command.Add(cmd); } public string Read() { return _doc.ReadDocument(); } } //concrete implementation class DocumentEditCommand : Command { private Document _editableDoc; private string _text; public DocumentEditCommand(Document doc, string text) { _editableDoc = doc; _text = text; _editableDoc.Write(_text); } override public void Redo() { _editableDoc.Write(_text); } override public void Undo() { _editableDoc.Erase(_text); } }