下令模式的学习
命令模式的学习
一个比较有意思的例子,来说明命令模式
Client :看电视的人
Invoker :遥控器
Command :电信号
具体命令 :遥控器上的按键对应的不同的电信号
Receiver :电视机
Command模式,对功能的调用和功能的实现进行解藕。功能的调用者不用知道具体的功能是怎样实现的,使用了接口,具有很大的灵活性,使代码稳健、可维护、可复用。 下面是一个简单的例子,首先建立一个接口ICommand,
然后是两个实现了这个接口和具体功能的实用类:public interface ICommand {
void execue();
}
public class Printer implements ICommand { public void execue() { System.out.println("printed!"); } } public class FileOpener implements ICommand { public void execue() { System.out.println("Open file"); } }
在下面的这个类中实现了命令模式:
public class SystemFunction { private List<ICommand> cmds = new ArrayList<ICommand>(); public SystemFunction() { cmds.add(new FileOpener()); cmds.add(new Printer()); } public void doWork() { // TODO Auto-generated method stub for(ICommand cmd:cmds) { cmd.execue(); } } public static void main(String[] args) { SystemFunction cmd = new SystemFunction(); cmd.doWork(); } }
使用List存储具体的命令对象,由于实现了接口,所以能够以接口来引用具体的对象,这样就体现了解藕和灵活性。
通过以上简单的代码演示,应该可以对Command模式有一个大概的认识,为实际的开发提供更多的思路。