设计模式
设计模式分为创建型模式、结构型模式和行为型模式。
创建型模式:创建对象。
结构型模式:把复杂结构分解为多个类,分解的是类本身(包括算法和属性)。
行为型模式:把复杂算法分解到多个类,分解的是算法。
命令模式的目的是把命令单独实现,而不是和具体组件绑定在一起,这样可以实现命令的复用,同时方便修改。
UML
示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| public class CommandPattern { public static void main(String[] args) { Receiver receiver = new Receiver(); Command command = new ConcreteCommand(receiver); Invoker invoker = new Invoker(command); invoker.call(); } }
class Receiver { public void action() { System.out.println("执行命令"); } }
interface Command { void execute(); }
class ConcreteCommand implements Command { private Receiver receiver;
public ConcreteCommand(Receiver receiver) { this.receiver = receiver; }
@Override public void execute() { receiver.action(); } }
class Invoker { private Command command;
public Invoker(Command command) { this.command = command; }
public void call() { command.execute(); } }
|