Can anyone explain with a simple example the Command Pattern? I tried searching on the internet, but I got confused.
public interface Command {
public void execute();
}
For the most part, commands are immutable and contain instructions that encapsulate a single action that is executed on demand. You might also have a RuntimeCommand that accepts instructions upon execution, but this delves more into the Strategy or Decorator Patterns depending on the implementations.
In my own opinion, I think it's very important to heed the immutable context of a command otherwise the command becomes a suggestion. For instance:
public final class StopServerCommand implements Command {
private final Server server;
public StopServerCommand(Server server) { this.server = server; }
public void execute() {
if(server.isRunning()) server.stop();
}
}
public class Application {
//...
public void someMethod() {
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(Event e) {
stopCommand.execute();
}
});
}
}
I personally don't really like commands. In my own experience, they only work well for framework callbacks.
If it helps, think of a command in a metaphorical sense; a trained soldier is given a command by his/her commanding officer, and on demand the soldier executes this command.
You can think of Command pattern workflow as follows.
Client calls Invoker => Invoker calls ConcreteCommand => ConcreteCommand calls Receiver method, which implements abstract Command method.
UML Diagram from dofactory article:
Key features:
Command declares an interface for all commands, providing a simple execute() method which asks the Receiver of the command to carry out an operation.
The Receiver has the knowledge of what to do to carry out the request.
The Invoker holds a command and can get the Command to execute a request by calling the execute method.
The Client creates ConcreteCommands and sets a Receiver for the command.
The ConcreteCommand defines a binding between the action and the receiver.
When the Invoker calls execute the ConcreteCommand will run one or more actions on the Receiver.
Code snippet:
interface Command {
void execute();
}
interface Receiver {
public void switchOn();
}
class OnCommand implements Command{
private Receiver receiver;
public OnCommand(Receiver receiver){
this.receiver = receiver;
}
public void execute(){
receiver.switchOn();
}
}
class Invoker {
private Command command;
public Invoker(Command command){
this.command = command;
}
public void execute(){
this.command.execute();
}
}
class TV implements Receiver{
public void switchOn(){
System.out.println("Switch on from TV");
}
}
class DVDPlayer implements Receiver{
public void switchOn(){
System.out.println("Switch on from DVDPlayer");
}
}
public class CommandDemoEx{
public static void main(String args[]){
// On command for TV with same invoker
Receiver receiver = new TV();
Command onCommand = new OnCommand(receiver);
Invoker invoker = new Invoker(onCommand);
invoker.execute();
// On command for DVDPlayer with same invoker
receiver = new DVDPlayer();
onCommand = new OnCommand(receiver);
invoker = new Invoker(onCommand);
invoker.execute();
}
}
output:
Switch on from TV
Switch on from DVDPlayer
Explanation:
In this example,
Command interface defines execute() method.
OnCommand is ConcreteCommand, which implements execute() method.
Receiver is an interface and implementers have to provide implementation for the methods.
TV and DVDPlayer are two types of Receivers, which are passed to ConcreteCommand like OnCommand.
Invoker contains Command. It's the key to de-couple Sender from Receiver.
Invoker receives OnCommand -> which calls Receiver (TV) to execute this command.
By using Invoker, you can switch on TV and DVDPlayer. If you extend this program, you switch off both TV and DVDPlayer too.
You can use Command pattern to
Decouple the sender & receiver of command
Implement callback mechanism
Implement undo and redo functionality
Maintain a history of commands
Have a look at this dzone and journaldev and Wikipedia articles.
Source code as Wikipedia page is simple, cleaner and self explanatory.
You can implement Undo and Redo if you follow the steps as quoted in this article
Here is another example you can use to understand how command pattern works, using real life scenarios: You cannot travel from one place to another by airplane without using the command pattern!
If you are a frequent traveler, all you care about as a client is to travel from where you are to another . you don't care about how the pilot will fly the plane or which airline will be available .. you cant really predict that. all you want is to get the the air port and tell them to take you to your destination.
But if you do that, your command to the airport authorities will be laughed at! they need you to supply a command object, which is your ticket. as much as you don't care about which airline or which plane type, when you are ready to fly, you need to supply a ticket command object. The invoker, which is the airport officials needs to check your command (ticket) so that they can validate it, undo it if it is fake, redo it if they made a mistake (without you having to go through the booking process all over).
In short , they want to have complete control of your command (ticket) before deciding whether or not to invoke or execute your command, which lets the airline (the receiver ) execute ( put you on a plane and take you to your destination) .
Mind you, your command (your ticket) already has the information of the receiver (airline) without which the airport officials wont even start to process your ticket in the first place.
The airport authorities could even have a bunch of tickets they are working on. they may choose to delay my ticket and let someone that came after me go through (invoke another persons ticket before mine)
Here is the code :
[TestClass]
public class Client
{
[TestMethod]
public void MyFlight_UsingCommandPattern()
{
var canadianAirline = new Airline();
AirlineTicket_Command myTicket = new MyAirLineTicket(canadianAirline);
var airportOfficials = new AirportOfficials_Invoker(myTicket);
airportOfficials.ProcessPasengerTicket_And_AllowPassengerToFly_Execute();
//assert not implemented
}
}
public class AirportOfficials_Invoker
{
private AirlineTicket_Command PassengerTicket { set; get; }
public AirportOfficials_Invoker(AirlineTicket_Command passengerTicket)
{
throw new NotImplementedException();
}
public void ProcessPasengerTicket_And_AllowPassengerToFly_Execute()
{
PassengerTicket.Execute();
}
}
public abstract class AirlineTicket_Command
{
protected Airline Airline { set; get; }
protected AirlineTicket_Command(Airline airline)
{
Airline = airline;
}
public abstract void Execute();
}
public class MyAirLineTicket : AirlineTicket_Command
{
public MyAirLineTicket(Airline airline)
: base(airline)
{
}
public override void Execute()
{
Airline.FlyPassenger_Action();
}
}
public class Airline
{
public void FlyPassenger_Action()
{
//this will contain all those stuffs of getting on the plane and flying you to your destination
}
}
My requirement is to perform a sequence of tasks (which can be re-used in several Usecases) each with its own exception flow. Found Command pattern's implementation logical here.
I am trying to make it like each action executed by the command (whether normal/alternate flow) can be an exception handler too. However, If the command is registered with another handler then this should be used. Any suggestions for improvement/correction are welcome.
public interface Command {
Result run() throws Exception;
Command onException(ExceptionHandler handler);
}
public class Result {
}
public interface ExceptionHandler {
void handleException(Exception e);
}
public interface Action {
Result execute() throws Exception;
}
public class BasicCommand implements Command {
private Action action;
private ExceptionHandler handler;
public BasicCommand(Action action) {
if (action == null) {
throw new IllegalArgumentException("Action must not be null.");
}
this.action = action;
this.handler = (ExceptionHandler) this.action;
}
#Override
public Command onException(ExceptionHandler handler) {
if (handler != null) {
this.handler = handler;
}
return this;
}
public Result run() throws Exception {
Result result = null;
try {
result = action.execute();
} catch (Exception e) {
handler.handleException(e);
}
return result;
}
}
public class BasicAction implements Action, ExceptionHandler {
private Object[] params;
public BasicAction(Object... params) {
this.params = params;
}
#Override
public Result execute() throws Exception {
// TODO Auto-generated method stub
return null;
}
#Override
public void handleException(Exception e) {
// TODO exception translation: prepare unchecked application. exception and throw..
}
}
public class Main {
public static void main(String[] args) throws Exception {
int param1 = 10;
String param2 = "hello";
// command will use the action itself as an exception handler
Result result = new BasicCommand(new BasicAction(param1, param2)).run();
ExceptionHandler myHandler = new ExceptionHandler(){
#Override
public void handleException(Exception e) {
System.out.println("handled by external handler");
}
};
// command with an exception handler passed from outside.
Result result2 = new BasicCommand(new BasicAction(param1, param2)).onException(myHandler).run();
}
}
Command Design Patterns decouples invoker of service and provider of service. In general scenario, say for eg., If Object A wants service of Object B, it'll directly invoke B.requiredService(). Thus, A is aware about B. In Command pattern, this coupling is removed. Here, there's an intermediate object known as Command, which comes into picture. Thus, A deals with Command object and command object deals with actual object B. This approach has several applications such as designing applications, which are :-
Accepts commands as requests.
Undoing requests.
Requests requests.
Creating macros.
Creating Task Executors and Task Managers.
For more information regarding, Command Design Pattern, I'll recommend https://en.wikipedia.org/wiki/Command_pattern.
For all other design patterns, refer to https://www.u-cursos.cl/usuario/.../mi_blog/r/head_first_design_patterns.pdf
I would try to give you another rough analogy here.
Suppose that one day God calls on you and tells you that the world's in danger and He needs your help to save it. Further helping you , He tells you that He has sent some superheroes on earth.
Since He doesn't know oops and hence He doesn't call them superheroes (doesn't provide you any interface or abstract class over them) but just tell you their names for ex - batman, superman, iron man and the powers they have.
He also says that in future He might send more such guys in future.
Now He assigns you special responsibility -> control them and for that provides you with seven hands. He doesn't fixes the task of each hand Himself but leaves it on you.
You want flexibility in assigning any hand control of any superhero's power and don't want to repeatedly change things through multiple conditions.
You are in a fix. What do you do now?
Enter Command Pattern.
Create an interface Command and has only one method execute() in it. Encapsulate every power of each superhero and make that implement Command for ex - IronManCreatesSuitCommand
Now you can assign any hand to any command at any time giving you lot more flexibility because now none of your hands cares about the specific task it has to do. You just assign it any command to it. It calls execute on it and the command takes care of everything else.
Now even when God sends any other superhero with different powers, you know what to do.
Related
Head First Design Patterns say:
The Command Pattern encapsulates a request as an object, thereby
letting you parameterize other objects with different requests, queue
or log requests, and support undoable operations.
Later the book said:
The semantics of some applications require that we log all actions and
be able to recover after a crash by reinvoking those actions. The
Command Pattern can support these semantics with the addition of two
methods: store() and load(). In Java we could use object serialization
to implement these methods, but the normal caveats for using
serialization for persistence apply.
How does this work? As we execute commands, we store a history of them
on disk. When a crash occurs, we reload the command objects and invoke
their execute() methods in batch and in order.
I am trying to come up with an example code. The code I wrote till now is:
class Client {
public static void main(String[] args) {
Command enableCommand = new EnableCommand();
enableCommand.execute();
}
}
interface Command {
void execute();
void store();
void load();
}
class EnableCommand implements Command {
public EnableCommand() {
}
#Override
public void execute() {
store();
System.out.println("Execute Command");
}
#Override
public void store() {
System.out.println("Storing on Disk");
}
#Override
public void load() {
// TODO Auto-generated method stub
}
}
How the load() function is supposed to work?
I have a method that needs to execute multiple tasks to achieve a bigger task. Each task could be around 20-30 lines of code, so I decided to have a class per task.
public void bigTask() {
TaskProcessor executor = new TaskProcessor();
executor.addTask(new Task1(some arguments here));
executor.addTask(new Task2(some other arguments here));
executor.addTask(new Task2(some other arguments here));
executor.run();
}
public interface Task {
public void execute();
}
public class Task1 implements Task {
#Override
public void execute() {
//Some code here
}
}
public class Task2 implements Task {
#Override
public void execute() {
//Some other code here
}
}
public class Task3 implements Task {
#Override
public void execute() {
//Some other code here
}
}
public class TaskProcessor implements Serializable {
private List<Task> tasksList;
public TaskProcessor () {
this.tasksList = new ArrayList<Task>();
}
public void addTask(Task task) {
this.tasksList.add(task);
}
public void execute() {
for (Task task : this.tasksList) {
task.execute();
}
}
}
For me, this code is like a command pattern, but I am not sure because the arguments for each task are of different types, unlike the traditional command pattern.
Do you think this could be considered a command pattern implementation?
Do you think this approach is OK for splitting a big method?
Thank you
Do you think this could be considered a command pattern implementation?
I think it is "command pattern" enough.
Do you think this approach is OK for splitting a big method?
We used a very similar approach to dissect long "sequences" small "Actions". But we added different kind of "containers". As in: sometimes I have a sequence of Actions that should continue to be executed, even when one entry fails. In other cases, the whole sequence should stop immediately. Another flavor is a sequence where each Action also has a an undo() method, so that the sequence container can do a rollback of all previous (passed) Actions when some Action fails.
Depending on your context, you might be "good to go", but I think you should at least consider what/if your indvidual Tasks can fail, and how your TaskProcessor container should react to failing steps.
In terms of structure, this code is an application of the Command design pattern. The mapping to the pattern participants in the Gang of Four book is as follows:
Task is the Command interface in the pattern, with its execute method;
Task1-3 are the concrete commands;
TaskProcessor is the Invoker, which "asks the command to carry out the request"
However, in terms of intent, there is a bit of a mismatch. The original intent of the Command Pattern as stated in the Gang of Four book is
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
However, the question "Do you think this approach is OK for splitting a big method?" suggests the goal is to provide a modular decomposition of a complex piece of computing, which isn't the same.
I have a set of subscribers that need to start when server starts up.
Right now I'm instantiating them and calling run method on them in Application.java.
Was thinking it would be wonderful if these get instantiated on their own, may be using custom annotation or by belonging to an interface (get all classes of interface and instantiate). This way anyone writing a new subscriber in future doesn't need to create the object and call run() on it.
Wondering if anyone has solved it earlier and whether it makes sense to do it.
Example:
I have an interface for event handlers:
interface EventHandler {
void process(String data);
}
And then implementation classes:
public class CoolEventHandler implements EventHandler {
public void process(String data) {
//handle cool event
}
}
public class HotEventHandler implements EventHandler {
public void process(String data) {
//handle hot event
}
}
And I have a subscriber service which listens to remote APIs and if there's data, it passes that to handler:
public class PollService {
public static void register(String API, EventHandler eventHandler) {
//create a thread to poll API
//and if data is received, call eventHandler.process()
}
}
At the start of my application I'm registering handlers in Application.java
PollService.register("/cool", new CoolEventHandler());
PollService.register("/hot", new HotEventHandler());
Tomorrow if there's a new handler, say WarmEventHandler, I'll have to call register again. I'm trying to avoid this last step. What would be the best way to register all classes of EventHandler?
I would like to call different code (callbacks) from within a background thread loop and use that background thread to perform the work. It would be similar to delegates in C#.
public class test {
private boolean keepRunning;
private boolean messageReady;
private MyClass myClass;
void LongBackgroundWork(){
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (keepRunning) {
if (messageReady){
myClass.callback(); // call different methods here
// to be decided at runtime and run on this worker thread
}
}
}
});
thread.start();
}
}
I want to use the background thread not the UI thread. I want to set a callback from within myClass to choose what code is called. It's easy in C# how to do it Java.
I don't have much experience in Java and don't understand what mechanism to use. Should I be using a handler? Can a handler run code on a background thread?
I'd wager you want to have a pattern where an event or some occurence happens and you need to initiate a code block somewhere.
A pattern that could help you is perhaps an Observer Wiki and firing off to the event. You can also check out this SO question here if you'd like: Delegate vs Callback in Java
In your case, I think you'd want to have someone handle the responsibility of what you have to do when a message is ready. So what you're looking for is someone to perform the action, once the event is read (message ready).
Take for example Class Foo is your container of listeners, or also called an Observer that will be notified of any events. You can have a list of callbacks here to some object that is responsible for your logic to do what you need to do next.
Then you would have an Observable object or a class that would implement some logic when notified. You could then have various class objects perform the necessary logic by implementing the callback function required.
Example:
// Observer
public class Foo {
// List of objects that implement Callbacks interface
private List<Callbacks> mList;
public Foo() {
// Initialize here
}
public void addListener(Callbacks cb) {
mList.add(cb);
}
public void notifyListeners() {
for ( Callback cb : mList) {
cb.onCallback();
}
}
// Public interface to be implemented by users
public interface Callback {
void onCallback();
}
}
Then just have a class implement this object and you can pass it along if you'd like.
// Bar implements Foo.Callback interface
public class Bar implements Foo.Callback {
public class Bar() {}
#Override
public void onCallback() {
// Perform logic here
}
}
Finally in your code, you'd just create the Foo object, add a listener, and notify them when it's time to fire your event.
if i understood you properly,you cant do this on UI thread, basically when android see Thread like this it will expect that it's a long operation however you can call it by AsyncTask or Handler
you can make something like this
private class MyAsyncTask extends AsyncTask<Void,Void,Void>{
protected Void doInBackground() {
MyClass myClass=new MyClass();
myClass.LongBackgroundWork();
}
return totalSize;
}
}
this is how yo can call your thread otherwise you have to use Handler instead
Handler handler=new Handler();
handler.post(new Runnable(){
MyClass myClass=new MyClass();
myClass.LongBackgroundWork();
})
I am trying to design a Java system that is simliar to the concept of c# delegates.
Here is the basic functionality i wish to achieve:
public class mainform
{
public delegate onProcessCompleted
//......
processInformation()
{
onProcessCompleted(this);
}
//......
}
//PLUGIN
public class PluginA
{
public PluginA()
{
//somehow subscribe to mainforms onProcessingCompleted with callback myCallback()
}
public void myCallback(object sender)
{
}
}
I have read through this site: http://www.javaworld.com/javaqa/2000-08/01-qa-0804-events.html?page=1
They make reference to implementing the whole 'subscription list' manually. But the code is not a complete example, and I'm so used to c# that I'm having trouble grasping how I could do it in java.
Does anyone have a working examle of this that I could see?
thanks
Stephanie
In Java you don't have function delegates (effectively method references); you have to pass an entire class implementing a certain interface. E.g.
class Producer {
// allow a third party to plug in a listener
ProducerEventListener my_listener;
public void setEventListener(ProducerEventListener a_listener) {
my_listener = a_listener;
}
public void foo() {
...
// an event happened; notify the listener
if (my_listener != null) my_listener.onFooHappened(new FooEvent(...));
...
}
}
// Define events that listener should be able to react to
public interface ProducerEventListener {
void onFooHappened(FooEvent e);
void onBarOccured(BarEvent e);
// .. as many as logically needed; often only one
}
// Some silly listener reacting to events
class Consumer implements ProducerEventListener {
public void onFooHappened(FooEvent e) {
log.info("Got " + e.getAmount() + " of foo");
}
...
}
...
someProducer.setEventListener(new Consumer()); // attach an instance of listener
Often you have trivial listeners that you create via an anonymous classes in place:
someProducer.setEventListener(new ProducerEventListener(){
public void onFooHappened(FooEvent e) {
log.info("Got " + e.getAmount() + " of foo");
}
public void onBarOccured(BarEvent e) {} // ignore
});
If you want to allow many listeners per event (as e.g. GUI components do), you manage a list which you usually want to be synchronized, and have addWhateverListener and removeWhateverListener to manage it.
Yes, this is insanely cumbersome. Your eyes don't lie to you.