Command Pattern Code Review

Define the Pattern Interface and Command Objects

Code Download

  • Download Description:command pattern download
  • .NET Framework:3.5
  • .NET Language:C#
  • Date Published:2009-07-01
  • Download Size:9 KB

Code Review

Code Walkthrough

Define the ICommand interface to be used as the "blueprint" for the main application classes.

interface ICommand { Receiver Receiver { get; set; }
void Execute(); void Redo(); void Undo(); }

This interface defines the Execute, Redo and Undo methods and has a local instance of type Receiver.

The Receiver class (object) represents the class that will have the code logic to actually execute the required command, and this is where all the work will be done.

The Paste class (object) represents a unique command that needs to be actioned.

class Paste : ICommand { public Receiver Receiver { get; set; }
public void Execute() { this.Receiver.Paste(); } public void Redo() { this.Receiver.Paste(); } public void Undo() { this.Receiver.Restore(); } }

This class inherits from the ICommand object, and therefore implements the Execute, Redo and Undo methods and has a local variable of type Receiver defined.

The Print class (object) represents another unique command that needs to be actioned.

class Print : ICommand { public Receiver Receiver { get; set; }
public void Execute() { this.Receiver.Print(); } public void Redo() { this.Receiver.Print(); } public void Undo() { Console.WriteLine("Cannot undo a Print!\n"); } }

And as before, this class inherits from the ICommand object, and therefore implements the Execute, Redo and Undo methods and has a local variable of type Receiver defined.

The difference here, between the Paste command and the Print command, is that the Print command does not have a logical Undo process. So nothing needs doing when this method is called.