I found this very interesting pattern on Martin Fowler's web page, so I decided to explore more and yank out some codes to see how useful and practical in real life situation. If you look at the name "DecoratedCommand", it basically means the combination of the Decorator and the Command patterns sort of joining together to form a very interesting pattern. Even though the code used to implement the Decorator pattern is not entirely matching the original pattern, the concept remains the same.
Let's look at the coding implementation because it tells us many things in there:
using System;
namespace Test
{
public interface ICommand
{
void Execute();
}
public class InvoiceCommand : ICommand
{
private Receiver receiver;
public InvoiceCommand(Receiver receiver)
{
this.receiver = receiver;
}
public void Execute()
{
receiver.Action(1);
}
}
public class AccountCommand : ICommand
{
private Receiver receiver;
public AccountCommand(Receiver receiver)
{
this.receiver = receiver;
}
public void Execute()
{
receiver.Action(2);
}
}
public class Receiver
{
public void Action(int Command)
{
switch(Command)
{
case 1:
Console.WriteLine("Invoice command action here ");
break;
case 2:
Console.WriteLine("Account command action here");
break;
}
}
}
public abstract class CommandDecorator
{
protected ICommand command;
public CommandDecorator(ICommand command)
{
this.command = command;
}
abstract public void Execute();
}
public class TransactionalDecorator : CommandDecorator
{
public TransactionalDecorator(ICommand command) : base(command) {}
public override void Execute()
{
Console.WriteLine("Do your transaction here");
command.Execute();
}
}
public class SecurityDecorator : CommandDecorator
{
public SecurityDecorator(ICommand command) : base(command) {}
public override void Execute()
{
Console.WriteLine("Do your security check here");
command.Execute();
}
}
class Invoker
{
private CommandDecorator _commanddecorator;
public CommandDecorator commanddecorator
{
get { return _commanddecorator; }
set { _commanddecorator = value; }
}
public void ExecuteCommand()
{
commanddecorator.Execute();
}
}
public class Client
{
public static void Main(string[] args)
{
Receiver r = new Receiver();
CommandDecorator cd = new TransactionalDecorator(new InvoiceCommand(r));
Invoker i = new Invoker();
i.commanddecorator = cd;
i.ExecuteCommand();
cd = new SecurityDecorator(new AccountCommand(r));
i.commanddecorator = cd;
i.ExecuteCommand();
}
}
}
1. The command pattern is exactly the same implemetation as the orginal pattern
2. The CommandDecorator captures the ICommand interface and acts as a layer to execute its own logic and the command object
3. The invoker captures the CommandDecorator object instead of the Command object as indicated in the original Command pattern.
4. Clients can now use the Invoker to execute code in the CommandDecorator, which in turns executes code of the Command object.
Hope ir helps