NOTE

Command Pattern

Command-pattern notes with a Java Course example, command objects, and a command invoker.

Software Architecture & Engineering1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Definition

2. UML

3. Java

3.1. Commands

  • Course
public class Course
{
    public void open()
    {
        System.out.println("open");
    }

    public void close()
    {
        System.out.println("close");
    }
}
  • ICommand
public interface ICommand
{
    void execute();
}
  • CloseCommand
public class CloseCommand implements ICommand
{
    private Course course;

    public CloseCommand(Course course)
    {
        this.course = course;
    }

    @Override
    public void execute()
    {
        this.course.close();
    }
}
  • OpenCommand
public class OpenCommand implements ICommand
{
    private Course course;

    public OpenCommand(Course course)
    {
        this.course = course;
    }

    @Override
    public void execute()
    {
        this.course.open();
    }
}

3.2. Command Invoker

  • Me

public class Me
{
    private List<ICommand> commands = new ArrayList<>();

    public void addCommand(ICommand command)
    {
        this.commands.add(command);
    }

    public void executeCommand()
    {
        for (ICommand command : commands)
        {
            command.execute();
        }
    }
}

3.3. Client

public class Client
{
    public static void main(String[] args)
    {
        Me me = new Me();
        Course course = new Course();
        me.addCommand(new OpenCommand(course));
        me.addCommand(new CloseCommand(course));
        me.executeCommand();
    }
}

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub