I'm trying to teach myself a new pattern, the command pattern, and came up with the following example. Looking for feedback.
public class BaseTool
{
private List<ICommand> CommandHistory = new List<ICommand>();
public string State = string.Empty;
public BaseTool()
{
}
public virtual void ExecuteCommand(ICommand cmd)
{
if (cmd.CanExecute(this))
{
cmd.Execute(this);
CommandHistory.Add(cmd);
}
}
public string PrintHistory()
{
StringBuilder sb = new StringBuilder();
foreach (ICommand cmd in CommandHistory)
{
sb.AppendLine(cmd.ToString());
}
return sb.ToString();
}
}
public class Tool : BaseTool
{
public Tool()
{
}
}
public interface ICommand
{
void Execute(BaseTool t);
bool CanExecute(BaseTool t);
}
public class PowerDownCommand : ICommand
{
private DateTime _executeTime;
public void Execute(BaseTool t)
{
if (!CanExecute(t))
{
throw new Exception("Error turning off the tool");
}
_executeTime = DateTime.Now;
t.State = "OFF";
}
public bool CanExecute(BaseTool t)
{
return (t != null);
}
public override string ToString()
{
return _executeTime.ToLongTimeString() + " : was powered down";
}
}
public class PowerUpCommand : ICommand
{
private DateTime _executeTime;
public void Execute(BaseTool t)
{
if (!CanExecute(t))
{
throw new Exception("Error turning on the tool");
}
_executeTime = DateTime.Now;
t.State = "ON";
}
public bool CanExecute(BaseTool t)
{
return (t != null);
}
public override string ToString()
{
return _executeTime.ToLongTimeString() + " : was powered up";
}
}
class Program
{
static void Main(string[] args)
{
Tool t = new Tool();
t.ExecuteCommand(new PowerUpCommand());
Thread.Sleep(1000);
t.ExecuteCommand(new PowerDownCommand());
Console.WriteLine(t.PrintHistory());
Console.Read();
}
}