From the course: Complete Guide to Java Design Patterns: Creational, Behavioral, and Structural

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Solution: The Command pattern

Solution: The Command pattern

So this is my solution to the command pattern exercise. The first thing I'm going to do is create an interface for executing commands. So I'm going to create a new Java class and I'm going to call it LightCommand. So I'm going to change class to interface. And in here, I'm going to define a single void method called execute. Then I'm going to create concrete implementations of this for turning the lights on and off. So I'll start with turning the lights on. So I'm going to create another new class and I'm going to call this one TurnOnLightCommand. And this class is going to implement the LightCommand interface. So first of all, this is going to have a field of type light. So I'm going to say private final Light light. And this is going to be set in a constructor. So I'm going to say public TurnOnLightCommand and pass in a light object. And inside the constructor, I'm going to say this.light equals light. And now I need to override the execute method. So I'm going to say @Override…

Contents