Command Pattern Code Review

Define the Invoker and Receiver Objects

Code Review

Code Walkthrough

The Invoker class (object) is called by the client and is used to action the required commands.

class Invoker { private Receiver m_receiver;
public String ClipBoard { private get; set; } public Int32 Count { get; private set; }
public Invoker(String name) { this.m_receiver = new Receiver(name); this.Count = 0; } public void Execute(ICommand command) { if (command is Paste) { this.m_receiver.ClipBoard = this.ClipBoard; } command.Receiver = this.m_receiver; command.Execute(); this.Count++; } public void Redo(ICommand command) { if (command is Paste) { this.m_receiver.ClipBoard = this.ClipBoard; } command.Receiver = this.m_receiver; command.Redo(); this.Count++; } public void Undo(ICommand command) { command.Receiver = this.m_receiver; command.Undo(); this.Count++; } public void Log() { Console.WriteLine("Logged {0} commands", this.Count); } }

Note the creation of the Receiver object, which will have the necessary methods defined to action the command. In this case, there is only one Receiver object used, but could define multiple Receiver objects, if required.

The Receiver class (object) contains the logic required to action the relevant command.

class Receiver { private String m_name = String.Empty; private String m_oldpage; private StringBuilder m_page = new StringBuilder();
public String ClipBoard { get; set; }
public Receiver(String name) { this.m_name = name; }
public void Paste() { this.m_oldpage = this.m_page.ToString(); this.m_page.Append(this.ClipBoard); this.m_page.Append("\n"); } public void Print() { Console.WriteLine("File {0} at {1}\n{2}", this.m_name, DateTime.Now.ToString(), this.m_page.ToString()); } public void Restore() { this.m_page.Length = 0; this.m_page.Append(this.m_oldpage); } }