Properties:
- Encapsulates set of actions to achive a task.
- A command can be executed to complete a task without need to know what it does.
Implementation:
- A Command interface declares method or methods that encapsulates actions.
- A Receiver is passed to a command object and does the actual work that is specific to certain task.
- Concrete Command class defines actual steps to achieve a certain task.
- Invoker invokes the commands objects.
- Client creates command objects and passes to invoker for execution.
Java Standard Library Implementations:
- java.lang.Runnable
- javax.swing.Action
Example Usage:
class ConcreteCommand extends Runnable{
Reveiver _receiver;
public ConcreteCommand(Reveiver _receiver){
this._receiver=receiver;
}
public void run(){
_reveiver.doAction();
System.out.println("Action is completed!")
_receiver.cleanUp();
}
}
public static void main(String[] args){
// invoker is responsible for executing the commands
ExecutorService executerService = new ThreadPoolExecutor(
5, 5, TimeUnit.MINUTES,new ArrayBlockingQueue<Runnable>(5, true));
//receiver does the actual work
Receiver receiver = new Receiver();
// Command object is created with receiver object passed to it
Runnable command = new ConcreteCommand(receiver);
// command is invoked
executerService.execute(command);
executerService.shutdown();
}
Comments
Post a Comment