NOTE
Command Pattern
Examples involving courses and command interfaces demonstrate the command pattern and how requests are wrapped as objects for execution.
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();
}
}
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub