概念
- 行为型设计模式,请求以命令的形式包裹在对象中,并传递给调动对象.
翻译: 1.将对象行为(执行过程)抽象为具体的类,然后与调用者组合(以属性的方式注入到调用者对象)
- 角色:调用者(Invoker),命令(Command)以及实现类,客户端.(CommandImpl本身就可以简化为具体命令,不一定需要Receiver)
- 源码应用:TreadPoolExecutor,Thread和Runnable
代码如下
//命令的实现类,可以等价于Runnable的实现类,可以再抽象一层Receiver,也可以不用.
public class CommandImpl implements Command {
Receiver receiver;
public CommandImpl(Receiver receiver) {
this.receiver = receiver;
}
public void run() {
System.out.println("run方法");
receiver.action();
}
}
//具体方法
public class Receiver {
void action(){
System.out.println("接收者方法!");
}
}
//调用者
public class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
/*调用命令的run方法,类似 Thread 类调用 Callable接口的run方法*/
public void run (){
command.run();
}
}
ThreadPoolExecutor execute
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
//将命令添加到队列中.(无接收者)
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
抽象过程
一个对象的行为可能有N种,假设有N个方法,如何把它封装成具体的命令呢? => 构建N个命令对象并实现统一的接口.那么我执行命令的时候,那就只需要 command.execute(),而不需要关心,具体的实现了,(屏蔽,调用者不需要关心具体的方法了) (命令模式 ,可以理解为生产消费者模式的一种行为消费的抽象过程.)
网友评论