[Design Patterns] Command

The “Command” is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time.

 

1. Command Pattern

A Command pattern encapsulates a request as an object.

 

2. Design

 

3. Participants

  • Command : interface for executing an operation
  • MyCommand : a concrete class which implements a Command interface
  • MenuItem : invoke the request: menu or button …
public interface ICommand
{
  void Execute();
}

public class MyCommand : ICommand
{
  public void Execute()  { }
}

 

4. Consequences

  • Command decopuples the object that invokes the operation from the one that knows how to perform it.

 

5. Example

public class Person
{
  public String Name { get; set; }
  public int Age { get; set; }
}

public interface ICommand
{
  void Execute(Person p);
}

public class NewCommand : ICommand
{
  public void Execute(Person p)
  {
    Console.WriteLine("Please enter the name:");
    p.Name = Console.ReadLine();
    Console.WriteLine("Please enter the age:");
    string ageStr = Console.ReadLine();
    int age = 0;
    Int32.TryParse(ageStr, out age);
    p.Age = age;
    Console.WriteLine($"New person - {p.Name}: {p.Age} years old.");
  }
}

public class HelloCommand : ICommand
{
  public void Execute(Person p)
  {
    Console.WriteLine($"Hello {p.Name}, You are {p.Age} years old.");
  }
}

 

public class Invoker
{
  public void InvokeAction(string cmdStr, Person p = null)
  {
    ICommand cmd = null;
    switch (cmdStr)
    {
      case "New": cmd = new NewCommand(); break;
      case "Hello": cmd = new HelloCommand(); break;
    }
    if (cmd != null)
    {
      cmd.Execute(p);
     }
  }
}

 

public static void Test()
{
  Invoker invk = new Invoker();
  Person p = new Person();
  invk.InvokeAction("New", p);
  invk.InvokeAction("Hello", p);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s