4

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.

8

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.

That can be a viable option, when it's available.
Commands tend to be coupled to the thing they're operating on [the receiver]. I've implemented commands as nested classes, which allows commands to have access to the outer class' privates.
(I write C#. If I were writing C++, I might declare commands as friend of classes that they execute on.)

But the option of implementing commands as nested classes in a receiver isn't always available. Commands may be developed by a different group than the one who developed the receiver. They may or may not have the permission to modify the the source code for the receiver, if they have access to it at all.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.