Command Design Pattern Tutorial

Command Design Pattern TutorialWelcome to my Command Design Pattern Tutorial! The Command design pattern allows you to store a list of commands for later use. With it you can store multiple commands in a class to use over and over.

I cover the basic pattern in numerous ways including descriptions, diagrams and code. We look into executing commands on numerous objects. We also explore how to undo commands.

All of the code follows the video. Between it and the video you should be an expert on the Command Pattern.

If you like videos like this, telling Google helps

Sharing is nice,

Code from the Video

ELECTRONICDEVICE.JAVA

public interface ElectronicDevice {
	
	public void on();
	
	public void off();
	
	public void volumeUp();
	
	public void volumenDown();
	
}

TELEVISION.JAVA (RECEIVER)

public class Television implements ElectronicDevice {

	private int volume = 0;
	
	public void on() {
		
		System.out.println("TV is on");
		
	}

	public void off() {
		
		System.out.println("TV is off");
		
	}

	public void volumeUp() {
		
		volume++;
		
		System.out.println("TV Volume is at: " + volume);
		
	}

	public void volumenDown() {
		
		volume--;
		
		System.out.println("TV Volume is at: " + volume);
		
	}
	
}

COMMAND.JAVA

// Each command you want to issue will implement 
// the Command interface

public interface Command {
	
	public void execute();
	
	// You may want to offer the option to undo a command
	
	public void undo();
	
}

TURNTVON.JAVA (COMMAND)

public class TurnTVOn implements Command {

	ElectronicDevice theDevice;
	
	public TurnTVOn(ElectronicDevice newDevice){
		
		theDevice = newDevice;
		
	}
	
	public void execute() {
		
		theDevice.on();
		
	}

	public void undo() {
		
		theDevice.off();
		
	}
	
}

TURNTVOFF.JAVA (COMMAND)

public class TurnTVOff implements Command {

	ElectronicDevice theDevice;
	
	public TurnTVOff(ElectronicDevice newDevice){
		
		theDevice = newDevice;
		
	}
	
	public void execute() {
		
		theDevice.off();
		
	}

	// Used if you want to allow for undo
	// Do the opposite of execute()
	
	public void undo() {
		
		theDevice.on();
		
	}
	
}

TURNTVUP.JAVA (COMMAND)

public class TurnTVUp implements Command {

	ElectronicDevice theDevice;
	
	public TurnTVUp(ElectronicDevice newDevice){
		
		theDevice = newDevice;
		
	}
	
	public void execute() {
		
		theDevice.volumeUp();
		
	}

	public void undo() {
		
		theDevice.volumenDown();
		
	}
	
}

DEVICEBUTTON.JAVA (INVOKER)

// This is known as the invoker
// It has a method press() that when executed
// causes the execute method to be called

// The execute method for the Command interface then calls 
// the method assigned in the class that implements the
// Command interface

public class DeviceButton{
	
	Command theCommand;
	
	public DeviceButton(Command newCommand){
		
		theCommand = newCommand;
		
	}
	
	public void press(){
		
		theCommand.execute();
		
	}
	
	// Now the remote can undo past commands
	
	public void pressUndo(){
		
		theCommand.undo();
		
	}
	
}

TVREMOTE.JAVA

public class TVRemote {
	
	public static ElectronicDevice getDevice(){
		
		return new Television();
		
	}
	
}

PLAYWITHREMOTE.JAVA

import java.util.ArrayList;
import java.util.List;

public class PlayWithRemote{
	
	public static void main(String[] args){
		
		// Gets the ElectronicDevice to use
		
		ElectronicDevice newDevice = TVRemote.getDevice();
		
		// TurnTVOn contains the command to turn on the tv
		// When execute() is called on this command object
		// it will execute the method on() in Television
		
		TurnTVOn onCommand = new TurnTVOn(newDevice);
		
		// Calling the execute() causes on() to execute in Television
		
		DeviceButton onPressed = new DeviceButton(onCommand);
		
		// When press() is called theCommand.execute(); executes
		
		onPressed.press();
		
		//----------------------------------------------------------
		
		// Now when execute() is called off() of Television executes
		
		TurnTVOff offCommand = new TurnTVOff(newDevice);
		
		// Calling the execute() causes off() to execute in Television
		
		onPressed = new DeviceButton(offCommand);
		
		// When press() is called theCommand.execute(); executes
		
		onPressed.press();
		
		//----------------------------------------------------------
		
		// Now when execute() is called volumeUp() of Television executes
		
		TurnTVUp volUpCommand = new TurnTVUp(newDevice);
				
		// Calling the execute() causes volumeUp() to execute in Television
				
		onPressed = new DeviceButton(volUpCommand);
				
		// When press() is called theCommand.execute(); executes
				
		onPressed.press();
		onPressed.press();
		onPressed.press();
		
		//----------------------------------------------------------
		
		// Creating a TV and Radio to turn off with 1 press
		
		Television theTV = new Television();
		
		Radio theRadio = new Radio();
		
		// Add the Electronic Devices to a List
		
		List<ElectronicDevice> allDevices = new ArrayList<ElectronicDevice>();
		
		allDevices.add(theTV);
		allDevices.add(theRadio);
		
		// Send the List of Electronic Devices to TurnItAllOff
		// where a call to run execute() on this function will
		// call off() for each device in the list 
		
		TurnItAllOff turnOffDevices = new TurnItAllOff(allDevices);
		
		// This calls for execute() to run which calls for off() to
		// run for every ElectronicDevice
		
		DeviceButton turnThemOff = new DeviceButton(turnOffDevices);
		
		turnThemOff.press();
		
		//----------------------------------------------------------
		
		/*
		 * It is common to be able to undo a command in a command pattern
		 * To do so, DeviceButton will have a method called undo
		 * Undo() will perform the opposite action that the normal
		 * Command performs. undo() needs to be added to every class
		 * with an execute()
		 */
		
		turnThemOff.pressUndo();
		
		// To undo more than one command add them to a LinkedList
		// using addFirst(). Then execute undo on each item until 
		// there are none left. (This is your Homework)
		
	}
	
}

RADIO.JAVA (RECEIVER)

public class Radio implements ElectronicDevice {

	private int volume = 0;
	
	public void on() {
		
		System.out.println("Radio is on");
		
	}

	public void off() {
		
		System.out.println("Radio is off");
		
	}

	public void volumeUp() {
		
		volume++;
		
		System.out.println("Radio Volume is at: " + volume);
		
	}

	public void volumenDown() {
		
		volume--;
		
		System.out.println("Radio Volume is at: " + volume);
		
	}
	
}

TURNITALLOFF.JAVA (COMMAND)

import java.util.List;

public class TurnItAllOff implements Command {
  List<ElectronicDevice> theDevices;
 
  public TurnItAllOff(List<ElectronicDevice> newDevices) {
	  theDevices = newDevices;
  }
 
  public void execute() {
 
    for (ElectronicDevice device : theDevices) {
      device.off();
    }
 
  }

  public void undo() {
	
	for (ElectronicDevice device : theDevices) {
	      device.on();
	    }
	
  }
}

47 Responses to “Command Design Pattern Tutorial”

  1. Punit says:

    Kool man, you are rocking dude.
    just one thing, do you have any plans to make some videos or tutorials for some tools ie.(git, ant, jenkins, performance tools).
    Including:-
    1.> how to work on them.
    2.> how to extend them (plugins and all).
    3.> how to take repository of them and start contributing and make them as our requirements.

    i did allot of search but didn’t found any tutorials for this. 🙁

    Thanks,
    Punit

    • admin says:

      Thank you 🙂 I plan to cover many of the Java tools and apis. Maven, Ant, git, J2EE, GlassFish, etc. Thank you for the request

      • Punit says:

        wow, kool also please include also include “how to extend them and how to contribute to them”. you can’t imagine how much i am eager to learn that, waiting for those videos.
        thank you thank you thank you. 🙂

  2. Punit says:

    also wanted to know, to make some open source software or languages (ie. scala, clojure, node.js etc etc.), what makes them possible?
    i mean what are the base of them, what are the things needs to be known while writing any kind of language and all?

    Thanks

    • admin says:

      I’ve thought about teaching how to make a custom language. If I get into that then I should probably cover OS design. Then if I get into that I should just start an electronics tutorial in which I start with capacitors and resistors and work into a functioning computer (I actually have that tutorial in the works)

      I’m going to now cover software engineering using Java (design patterns, oop principles, UML, java architecture, etc.) Then I’ll move into Java Android, J2EE, Java Networking, and all of the popular Java APIs. After that I’ll probably start messing with electronics, building computers from scratch and other stuff like that.

      Thanks for the requests 🙂 Derek

      • punit says:

        just one question, is there anything which you don’t know. hehehehe 🙂 🙂 🙂 🙂 🙂

        how to learn all these things man, you rocks.
        such a great man, i would say.

        keep doing, i never thought even in dreams also that i am going to make a computer or operating system. 🙂

        • admin says:

          We all have the ability to learn. We just need to figure out how our brains best process information. I used to be a terrible student. Over the course of many years I figured out I learned better when information was given to me very quickly. Then after I learned to speed read I was able to consume information of any type quickly. Believe me I’m not all that smart 🙂

  3. Salah says:

    I hope that you will continue and introduce for us more advanced topics really I can’t stop watching your tutorials man you like drugs for me 🙂

    • admin says:

      Thank you 🙂 I’ll definitely cover software engineering using Java. Then I’ll combine Java with C to do more advanced stuff. A never ending supply of videos like that are in the works. I hope to have an entire software engineering course available by the end for free. It should be fun. I always wanted to be the Khan Academy of programming

  4. Punit says:

    one more question i do have, want to know is this possible?
    i have a netgear router, we are using 4 systems with that, in the router configuration page we can look, who is connected to the network.
    but the problem is if somebody put some downloading, we can’t see that there, i asked this on netgear forum also, but they don’t have any plugin which can tell this.
    so is that possible using java, we can figure out if someone has putted any downloading?

    • admin says:

      Do you want to monitor any time somebody downloads something from your site? If you set a site up the right way you can monitor pretty much everything they do on your site. That is best handled using AJAX techniques with PHP and either JavaScript or JQuery. I cover that in my JavaScript and JQuery tutorials

      • Punit says:

        No, not on my site.
        i have a router, and we are 4 persons connect to that router and use internet.
        but someone put some downloading on it’s machine, it makes the internet speed slow.
        that i want to monitor, if someone putted some downloading.
        just like we open router page: http://192.168.1.1/, here we can see which machines are connected to the router.

  5. Would it be within the bounds of the Design Pattern to implement a DeviceController with many Press() functions, that could correspond to many buttons on one Remote?

    It would store an array or list of Commands, and could execute according to which button was pressed.

    • admin says:

      Yes you can definitely do that. As you’ll see later in this tutorial that the design patterns are just a guide and can be greatly improved upon by adding features. My Interpreter design patterns tutorial is a great example of an enhanced pattern. Thank you for the great question 🙂

  6. Vaibhav Krishan says:

    Great Tutorial. Helped a lot in learning the concepts.

    Do you have any video’s on combining two different design patterns??

  7. Anonymous says:

    Thank You for putting together all these videos. It really helps. Your teaching style is really good. Thank You Again…

  8. Kapil says:

    Hi Derek,

    One request some tutorials on MAVEN would be really helpful. 🙂

    Thanks in advance

    • Derek Banas says:

      I added that request to the list. It is coming soon. Thanks for the request 🙂

    • Kapil says:

      Hi Derek,

      Sorry for this novice question, but I’m really curious to know the purpose of “Command Pattern”, just as you have always been explaining the purpose of each design pattern in your video tutorials, would be great if you can share some instances where in to use “Command Pattern”. Basically the fundamental reason to use this pattern over others. 🙂

      Thanks a lot

      • Derek Banas says:

        Hi,

        That is a very good question. You’d basically use the Command Pattern when you need to decouple the object that needs actions to be performed from the objects that perform those actions. Most design patterns try to decouple code. The goal is to have objects request an action to be performed and know that the object knows exactly how to perform those actions. The objects don’t need to know how the job is done they just want it done.

        Does that help?

  9. Max says:

    Hi Derek, I wonder what is your own strategy to learn new technologies, so that you are able to use them in practice on advanced level? Do you recommend to read like 1000 pages books?
    Thanks!

    • Derek Banas says:

      I always focused on learning one language completely before moving on to others. If I was starting today I’d figure out what 3 / 4 languages I need to be able to accomplish what I want to do. This is what I do and the languages I picked (They May be Different from Yours)

      I make Shopping Cart Sites : PHP, JavaScript / JQuery
      I make Android Apps : Java, C / C++

      I focused on those languages and got good with them. Yes I read 1,000 page books and numerous articles / APIs online. I’m a big believer in getting great at a few languages rather then learning 40% of 10 languages. I can do just about anything imaginable with just the 4 above.

      I hope that helps

  10. Burale says:

    Why did you use TVRomote class just to return Television in this way: ElectronicDevice newDevice = TVRemote.getDevice(); when you could have used:
    ElectronicDevice newDevice = new Television(); am I missing something?

    By the way thanks for great tutorials, I have enjoyed the first 12 design pattern tutorials and plan to watch the rest of.

    • Derek Banas says:

      Thank you 🙂 I didn’t fully develop the TVRemote. The idea was to have numerous versions of getDevice, so that I could control things other then just the television. Sorry that I didn’t explain that better.

  11. Burale says:

    That explains it. Thanks

  12. Henrik Jess says:

    Hi,

    Could it be possible to zip all the code into one file?

  13. Tulasi says:

    Great postings! Thankyou, they were very helpful.

  14. Oscar Sanchez says:

    this is a really good tutorial video, Thanks

  15. Tuhin Chatterjee says:

    Hi Derek,

    First of all, I sincerely admire and thank you for all the effort you have put in with these videos. I’ve recently begun going through some of the one on Design Patterns, and have found them quite well done and easy to follow.

    The question I have isn’t pertaining to this particular pattern, or any pattern per se, but rather about a polymorphism-related coding practice that I’ve observed in your code.

    In this video, take for example any of the TV Command classes. These commands are specifically meant for a television, yet when using object composition to store a TV object inside the class, you choose to define the variable as type ElectronicDevice, and not Television. Is there a specific reason for this?

    Thanks in advance,
    Tuhin

    • Tuhin Chatterjee says:

      Just to add a bit more detail, my question is not why one should use polymorphism, but rather whether there is any use/specific reason in the case I mentioned. I’ve noticed you do this inside the main method, often. In this case, with the statement

      ElectronicDevice newDevice = TVRemote.getDevice();

      Thanks

    • Derek Banas says:

      Hi Tuhin,

      Thank you for the nice compliments 🙂 I’m glad you have found them useful.

      The goal here was to be able to use an unlimited number of possible remotes with an unlimited number of different electronic devices. That is why I didn’t call it Television because I may want to use a remote with something other then a television. I hope that helps.

      • Tuhin Chatterjee says:

        Hi Derek,

        Thanks for the reply. I think what you wanted to achieve was to hide the individual device classes (TV, Radio, etc.) from the user, by relying on the generic ElectronicDevice Interface. That explains why the data members inside the TC commands are of ElectronicDevice type as well—the user wouldn’t know about class TV’s existence in the first place!

        Thanks!

        P.S. – I might bug you now and then with questions I have

        Tuhin

Leave a Reply

Your email address will not be published.

Google+