I trying to learn the Command design pattern, I already know how it works and where it is used, but I'm a little bit confused about the implementation.
So I know we need to set the context by passing the object to the constructor or as an argument to the execute()
function. What I don't understand is why do we need to define all the commands as separate classes and not as nested classes of the class we want to execute them on. Since we already need to know what the object is when creating the command (if we set the context in the constructor) what's the point of having so many separate classes?
For example:
This is the typical implementation I usually see (from this tutorial, I simplified it a little bit):
public class Television {
public void on() {
System.out.println("TV is on");
}
}
public interface Command {
public void execute();
}
public class TurnTVOn implements Command {
ElectronicDevice theDevice;
public TurnTVOn(ElectronicDevice newDevice){
theDevice = newDevice;
}
public void execute() {
theDevice.on();
}
}
//somewhere in main
Television newDevice = TVRemote.getDevice();
Command onCommand = new TurnTVOn(newDevice);
onCommand.execute()
Why not do it like this:
public interface Command {
public void execute();
}
public class Television {
public void on() {
System.out.println("TV is on");
}
public class TurnTVOn implements Command {
public void execute() {
on();
}
}
}
//somewhere in main
Command onCommand = TVRemote.getDevice().TurnTVOn;
onCommand.execute()
The answer is probably obvious, but I'm a beginner and asking "stupid" questions when I don't completely understand something instead of just going with it helps me a lot.