Scan with Phone

Scan to instantly open and share this page on your mobile device.

Link copied to clipboard!

Command

Encapsulate request as object (action + undo).

C#

// Command interface (Execute + Undo)
interface ICommand
{
	void Execute();
	void Undo();
}

// Receiver holding the actual state
class Counter
{
	public int V;
}

// Concrete Command
class IncCommand : ICommand
{
	private readonly Counter _counter;
	private readonly int _step;

	public IncCommand(Counter c, int step)
	{
		_counter = c;
		_step = step;
	}

	public void Execute() => _counter.V += _step;
	public void Undo()    => _counter.V -= _step;
}

// Usage
var counter = new Counter();
var cmd = new IncCommand(counter, 5);
cmd.Execute(); // V = 5
cmd.Undo();    // V = 0
next