标签:
publicclassReceiver{
// 真正执行命令相应的操作
publicvoid action(){
System.out.println("执行操作");
}
}
public interface Command{
// 执行方法
void execute();
}
publicclassConcreteCommand implements Command{
//持有相应的接收者对象
privateReceiver receiver = null;
publicConcreteCommand(Receiver receiver){
this.receiver = receiver;
}
@Override
publicvoid execute(){
//通常会转调接收者对象的相应方法,让接收者来真正执行功能
receiver.action();
}
}
publicclassInvoker{
//持有命令对象
privateCommand command = null;
publicInvoker(Command command){
this.command = command;
}
// 行动方法
publicvoid action(){
command.execute();
}
}
publicclassClient{
publicstaticvoid main(String[] args){
//创建接收者
Receiver receiver =newReceiver();
//创建命令对象,设定它的接收者
Command command =newConcreteCommand(receiver);
//创建请求者,把命令对象设置进去
Invoker invoker =newInvoker(command);
//执行方法
invoker.action();
}
}
public interface Runnable{
public abstract void run();
}
//命令模式在调用者这里不需要继承Runnable接口,但是这里考虑到实际情况,比如方便性等,继承了Runnable接口,实现了run方法,这个是Thread自身的运行run的方法
classThread implements Runnable{
privateRunnable target;
publicThread(Runnable target){
this.target = target;
}
public synchronized void start(){
if(threadStatus !=0||this!= me)
thrownewIllegalThreadStateException();
group.add(this);
start0();//这个是本地方法,调用run方法
if(stopBeforeStart){
stop0(throwableFromStop);
}
}
//可选
publicvoid run(){
if(target != null){
target.run();
}
}
}
标签:
原文地址:http://www.cnblogs.com/Doing-what-I-love/p/5621165.html