Decorator over Inheritance hierarchy
public class Command : ICommand
{
public bool CanExecute(object parameter)
{
// normal can execute version
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
// normal execute version
}
}
public class AuditedCommand:Command
{
public bool CanExecute(object parameter)
{
// audited can execute version
return base.CanExecute(parameter);
}
public void Execute(object parameter)
{
// audited execute version
base.Execute(parameter);
}
}
public class SecureCommand : Command
{
public bool CanExecute(object parameter)
{
// Secure can execute version
return base.CanExecute(parameter);
}
public void Execute(object parameter)
{
// Secure execute version
base.Execute(parameter);
}
}
public class Command : ICommand
{
public bool CanExecute(object parameter)
{
// normal can execute
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
// normal execute
}
}
public abstract class CommandDecorator : ICommand
{
private ICommand _command;
public CommandDecorator(ICommand command)
{
this._command = command;
}
public virtual bool CanExecute(object parameter)
{
return _command.CanExecute(parameter);
}
// should be a wrapper to the property in the base class
public event EventHandler CanExecuteChanged;
public virtual void Execute(object parameter)
{
_command.Execute(parameter);
}
}
public class AuditedCommand:CommandDecorator
{
public AuditedCommand(ICommand command):base(command)
{
}
public override bool CanExecute(object parameter)
{
// Audit behaviour goes here
return base.CanExecute(parameter);
}
public override void Execute(object parameter)
{
// Audit behaviour goes here
base.Execute(parameter);
}
}
public class SecureCommand : CommandDecorator
{
public SecureCommand(ICommand command):base(command)
{
}
public override bool CanExecute(object parameter)
{
// Secure behaviour goes here
return base.CanExecute(parameter);
}
public override void Execute(object parameter)
{
// Secure behaviour goes here
base.Execute(parameter);
}
}
// Here is how you compose your commands
ICommand auditedDecorator = new AuditedCommand(command);
ICommand secureDecorator = new SecureCommand(command);
ICommand auditedSecureDecorator = new SecureCommand(auditedDecorator);