介绍

命令模式是一个高内聚的模式, 其定义为: Encapsulate a request as an object,thereby letting you parameterize clients with different requests,queue or log requests,and support undoable operations.(将一个请求封装成一个对象, 从而让你使用不同的请求把客户端参数化, 对请 求排队或者记录请求日志, 可以提供命令的撤销和恢复功能。 ) —— 设计模式之禅 第2版

这个模式很常见,Runnable 就是这种模式的实现

实现

Command

  1. package cn.zjm404.stu.dp.behavior.command;
  2. public interface ICommand {
  3. public void execute();
  4. }
  1. package cn.zjm404.stu.dp.behavior.command;
  2. public class ConcreteCommand1 implements ICommand{
  3. @Override
  4. public void execute() {
  5. System.out.println("hello world");
  6. }
  7. }

Client

  1. package cn.zjm404.stu.dp.behavior.command;
  2. public class Client {
  3. public static void main(String[] args) {
  4. ICommand command = new ConcreteCommand1();
  5. command.execute();
  6. }
  7. }

参考

  • 设计模式之美