java设计模式之Command模式
2010-08-15 16:57
155 查看
Command模式是对操作的统一封装。
典型的Command 模式需要有一个接口.接口中有一个统一的方法,这就是"将命令/请求封装为对象":
public interface Command {
public abstract void execute ( );
}
具体不同命令/请求代码是实现接口Command,下面有二个具体命令
public class IntegerCommand implements Command {
public void execute( ) {
//do IntegerCommand 's command
}
}
public class CharCommand implements Command {
public void execute( ) {
//do CharCommand 's command
}
}
通常可以直接调用这两个Command,但是使用Command 模式,我们要将他们封装到黑盒子List 里去:
public class producer{
public static List produceRequests() {
List queue = new ArrayList();
queue.add( new IntegerCommand () );
queue.add( new CharCommand () );
return queue;
}
}
这两个命令进入List 中后,已经失去了其外表特征,调用Command 模式:
public class TestCommand {
public static void main(String[] args) {
List queue = Producer.produceRequests();
for (Iterator it = queue.iterator(); it.hasNext(); )
//取出List 中东东,其他特征都不能确定,只能保证一
个特征是100%正确,
// 他们至少是接口Command 的"儿子".所以强制转换
类型为接口Command
((Command)it.next()).execute();
}
}
调用者基本只和接口打交道,不合具体实现交互,这也体现了一个原则,面向接口编程;
典型的Command 模式需要有一个接口.接口中有一个统一的方法,这就是"将命令/请求封装为对象":
public interface Command {
public abstract void execute ( );
}
具体不同命令/请求代码是实现接口Command,下面有二个具体命令
public class IntegerCommand implements Command {
public void execute( ) {
//do IntegerCommand 's command
}
}
public class CharCommand implements Command {
public void execute( ) {
//do CharCommand 's command
}
}
通常可以直接调用这两个Command,但是使用Command 模式,我们要将他们封装到黑盒子List 里去:
public class producer{
public static List produceRequests() {
List queue = new ArrayList();
queue.add( new IntegerCommand () );
queue.add( new CharCommand () );
return queue;
}
}
这两个命令进入List 中后,已经失去了其外表特征,调用Command 模式:
public class TestCommand {
public static void main(String[] args) {
List queue = Producer.produceRequests();
for (Iterator it = queue.iterator(); it.hasNext(); )
//取出List 中东东,其他特征都不能确定,只能保证一
个特征是100%正确,
// 他们至少是接口Command 的"儿子".所以强制转换
类型为接口Command
((Command)it.next()).execute();
}
}
调用者基本只和接口打交道,不合具体实现交互,这也体现了一个原则,面向接口编程;
相关文章推荐
- Command设计模式和java回调机制的异同
- java设计模式(十七)——命令模式(Command)
- Java设计模式 Design Pattern:命令模式 Command Pattern
- Java23种设计模式案例:命令模式(Command)
- java设计模式之Command
- java设计模式进阶_command
- Java设计模式——命令模式(Command)
- Java设计模式 Design Pattern:命令模式 Command Pattern
- 【设计模式 java】——命令模式(Command)
- Java设计模式 Bridge(桥接)Adapter,command,State,Mediator,Facade
- 浅谈Java设计模式(十八)命令模式(Command)
- JAVA设计模式九:--Command(命令模式)
- java设计模式18——命令模式(Command)
- Java设计模式(20)——行为模式之命令模式(Command)
- JAVA--命令模式(Command)--设计模式十八
- JAVA设计模式(18) —<行为型>命令模式(Command)
- Java设计模式之从[打飞机游戏中的控制器]分析命令(Command)模式
- Java开发中的23种设计模式详解----命令模式(Command)
- java设计模式之命令模式Command
- java设计模式-command模式