介绍
命令模式是一个高内聚的模式, 其定义为: 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
package cn.zjm404.stu.dp.behavior.command;public interface ICommand {public void execute();}
package cn.zjm404.stu.dp.behavior.command;public class ConcreteCommand1 implements ICommand{@Overridepublic void execute() {System.out.println("hello world");}}
Client
package cn.zjm404.stu.dp.behavior.command;public class Client {public static void main(String[] args) {ICommand command = new ConcreteCommand1();command.execute();}}
参考
- 设计模式之美
