Free Essay

Command Design Pattern


Submitted By bigtruck88
Words 1146
Pages 5
Command Design Pattern
* What is the Command Desgn Pattern (CDP) * Object Interaction and Command Object Hierarchy * Command Pattern generic UML * Recorded demonstration * Java example code * What are the benefits/drawbacks of the CDP
The intent of this presentation is to provide a walk through and recorded demonstration of the command design pattern.
What is the Command Design Pattern? * A Behavioral design pattern * An object is utilized to represent and encapsulate information * The information includes method name, object owning method, and method value parameters * The information can be called immediately or at a later time
The command pattern is a behavioral design pattern in which an object is utilized to represent and encapsulate information (Banas, 2012). The interesting thing about the command design pattern is that it can allow one to store lists of commands which can be called immediately or at a later time.
What is the Command Design Pattern? * Client specifies which command to run when the execute() method is invoked on one of the encapsulated methods * An object named “Invoker” transfers the Command to a separate object named “Receiver” which executes the correct code
The command pattern allows the client to determine which command to run when the execute method is invoked in the command interface (Kuchana, 2004). After the command is “invoked” to execute, he concrete command that is identified transfers the command to the receiver to execute the correct command (Kuchana, 2004). This will all be demonstrated in upcoming slides.
Core Object Interaction and Command Object Hierarchy

Both UML designs in this slide are taken from the e-book “Software Architecture Design Patterns in Java”, figures 30.1 and 30.2 respectively (Kuchana, 2004).
The first (top) design is intended to demonstrate object interaction prior to implementing the command design pattern. In this object oriented design, an application uses different objects to handle requirements (Kuchana, 2004). Implementation of the application relies on appointed objects whch will “invoke methods on these objects by passing required data as arguments” (chapter 30, p. 1)
The second (bottom) design is intended to demonstrate the command object hierarchy. In this figure the command object is the abstraction in which the method declaration is “execute” which (in the case of this UML design) is implemented by the two implementor (command) concrete classes (Kuchana, 2004).

Command Pattern UML

Putting it all together…
The UML diagram (Kuschana, 2004, figure 30.3) above demonstrates the combination of the core object interaction and the command object hierarchy. In this example I use a Device as the Receiver. A device could be a light, a television, a computer, or a radio, basically anything with an on/off switch, up/down volume or anything else which has a command that can undo or redo. The client sends instructions through the main method. The invoker is the control button which could be on a remote control. The Command Interface executes the commands upon the Invoker action, which in this case is a button click. The concrete commands are DeviceOn and DeviceOff which are self-explanatory. Many more commands could be added such as turn volume up/down, resize picture, or even undo last command. This takes us back to the receiver which is the device and after the commands are executed the device will respond accordingly.
Demonstrating the Remote Control
Java example code * Device on/off, volume up/down * Please review the code sample embedded
As demonstrated in the recorded example of implementing the command design pattern, the code was copied and pasted on a Word document which is embedded in this slide for your review. I added volume up and down concrete command classes in the code examples as well. This required an addition to the device class as well.
//Client class public class Client {

public static void main(String[] args) { ControlButton controlButton = new ControlButton();

Device aDevice = new Device();

Command deviceOn = new DeviceOnCommand(aDevice); Command deviceOff = new DeviceOffCommand(aDevice);

//switch on controlButton.setCommand(deviceOn); controlButton.clickButton(); System.out.println("Device is on");

//switch off controlButton.setCommand(deviceOff); controlButton.clickButton(); System.out.println("Device is off"); }

//Invoker class public class ControlButton { private Command command; public void setCommand (Command command) { this.command = command; } public void clickButton() { command.execute(); }


//Receiver class public class Device {

private int volume = 0; private boolean on; public void turnOn() { on = true; } public void turnOff() { on = false; } public void volumeUp(){ volume++; System.out.println("Device volume is at " + volume); } public void volumeDown() { volume--; System.out.println("Device volume is at " + volume); }


//Command Interface public interface Command { public void execute();

} -------------------------------------------------------------------------------------------------------------------------------------
//Concrete command class 1 public class DeviceOnCommand implements Command{

Device device; public DeviceOnCommand(Device device) { this.device = device; } public void execute() { device.turnOn(); }


//Concrete command class 2 public class DeviceOffCommand implements Command{

Device device; public DeviceOffCommand(Device device) { this.device = device; } public void execute() { device.turnOff(); }


//Concrete command 3

public class TurnDeviceUp implements Command {

Device aDevice; public TurnDeviceUp(Device newDevice){ aDevice = newDevice; } @Override public void execute() { aDevice.volumeUp(); } }

//Concrete command 4

public class TurnDeviceDown implements Command {

Device aDevice; public TurnDeviceDown(Device newDevice){ aDevice = newDevice; } @Override public void execute() { aDevice.volumeDown(); } }
What are the ‘benefits’ of the Command Design Pattern? * Allows a list of commands to be set aside for later use * Classes are excellent place to store executable procedures * Undo procedures for past commands can be implemented * If a history of requests is needed
What are the ‘drawbacks’ of the Command Design Pattern? * Many small classes must be created to store list of commands which can make the design seem very cluttered * Adding more operations leads to more concrete command classes * As many commands are added, determining which Command to use may lead to possible maintenance issues for the central controller
During the briefing we discussed: * What is the Command Desgn Pattern (CDP) * Object Interaction and Command Object Hierarchy * Command Pattern generic UML * Gave a Live demonstration * Java example code * What are the benefits/drawbacks of the CDP
* Please ask any questions by replying to my Command Pattern Design Presentation thread
Banas, D. (2012). Command pattern design tutorial. Retrieved from:
Grand, M (2002) Patterns in java, volume 1: A catalog of reusable design patterns illustrated with UML, second edition. John Wiley & Sons. Retrieved from: James (2011). Design patterns uncovered: The command pattern. JamesSurge. Retrieved from: Kuchana, P. (2004) Software architecture design patterns in Java. Auerbach Publications. Retrieved from: Sierra, K., Robson, E., Bates, B., Freeman, E. (2004). Head first design patterns. SafariBooks. Retrieved from:

Similar Documents

Free Essay

Design Patterns

...generic system represents all the systems whether they are physical, sentient or more abstract. All the system follows the rules of the generic system. This system can be implemented during software development processes which helps all the processes to adapt to every software environment easily. Introduction: In software development , design phase is one of the important phase which takes lots of time and it is very hard to satisfy the end user regarding designing. Therefore this designing phase starts from beginning the of software development process till the end of the project. Therefore keeping in mind regarding the user needs and evolvement of new techniques each day, the generic system of design and development is introduced. By making the system generic, it becomes very easy for any of the software development company to adapt with the new working environment. Problem description: To develop a generic system design that helps to monitor the entity life history of any particular enitity and to show how this design is used in the administration system of academic conference. Objective: The main objective is to make a generic system design that can be implemented in the administration of any of the organization with few customization. => The generic system will be used to monitor the administration system and to keep track of the progress of any event in the administration system. =>To make the progress chart that helps to give clear idea about progress in the event. ...

Words: 750 - Pages: 3

Free Essay


...Paradox Therapy Paradoxes gure prominantly in this book, but most of them are purely intellectual. Paradoxical statements are apparent impossibilities that seem well supported by apparently good arguments. Interestingly, there are paradoxical commands as well as paradoxical statements. A very simple example is the command \don't follow this command!" Whatever you choose to do seems to violate the command. In order to obey it you must disobey it, but in disobeying it, you seem to obey it. Now, at rst it might seem that such a command is rather silly and easy to ignore. But suppose you are in the army and the command is given by a superior ocer, or you're a child and the command is given by a parent, or you're in love and the command is given by your lover. In short, imagine that the command occurs in a markedly unequal relationship. Second, suppose that you can't step outside the situation to point out the absurdity of the command. There is no judge that you can appeal to. Then you would be in a major bind indeed. You would be in what psychologists call a \double bind": Anything you do can and will be used against you. Thus we see the three ingredients of a paradoxical command or double bind: (1) a strong complementary or asymmetrical relationship (ocer-subordinate) (2) that can't simply be terminated (because of society, laws, and so on) and (3) an apparently meaningful but logically contradictory order. A realistic example of a double bind is described...

Words: 910 - Pages: 4

Free Essay

Nt2580 It

...Password Step 4 Router(config-line)# Step 11 Yes it ask for a password and it work with clscopress Step 12 Barney works Config router ip Step 4 It says unassigned Step 10 The ip is Step 11 Yes it did Config SSH Step 4 R1 config-line # Step 7 Config-line now I am in config Step 11 It connect me to R2 user command Terminal history Step 5 It shows, 3 subnets/[120/1] via, 00:45:35 Step 6 I see 5 commands I put in Step 8 I see two commands Rebuild a config Step 2 Ip,,hostname clock rate 1536000, password ciscopress, router config,its shutdown on each Step 3 Yes the ping worked Step 4 No it didn’t work Step 5 No it didn’t work Step 6 Yes it did work SSH and Telnet Step 1,,,,, Step 2 Yes for use no for enable mode Step 3 SSh and telnet Step 4 Step command incomplete Basic router config I can not find this lab on here. Switch and router security Step 2 No not any subcommand showed up Step 3 No the same happened here Subnetting lab 3 Step 1 I have no clue Step 9 No it does not...

Words: 266 - Pages: 2

Free Essay

It320 Assignment 2

...1. O IOS 2. L command-line interface (CLI) 3. I user EXEC mode 4. R privileged EXEC mode 5. S global configuration mode 6. A interface configuration mode 7. N routing protocol configuration mode 8. Q IOS image 9. B feature set 10. C ROM monitor /ROMMON 11. T boot ROM 12. D power-on self test (POST) 13. G bootstrap 14. J configuration register 15. U boot field 16. H boot system command 17. M setup mode 18. F host name 19. P console password 20. E enable password 21. K command recall Concept Questions Pg. 24 1. Attach a rollover cable to the PC’s COM port and then use either the Console port or the Auxiliary port on the router. The Console port is preferred because messages from the router are logged on this line. The second way is to use the Auxiliary port for remote access and can also be used if the Console port is damaged or not responding. The third way to access the CLI is through Telnet. 2. The user EXEC can only use a certain amount of commands and the user EXEC can’t configure anything on the router. The privileged EXEC can use every command and can configure the router anyway that person wants. 3. First it’s the platform in which the image runs on, second is the special features that are supported in the image, and last is where the image runs or whether it’s become a zipped or compressed file. 4. ROMMON is not IOS, so it doesn’t accept IOS commands, and it cannot route...

Words: 354 - Pages: 2

Free Essay

Lab 4.1: Using Linux Command-Line Basics

...Labs Lab 4.1: Using Linux Command-Line Basics What is the purpose? This lab demonstrates how to redirect data from a process and how to identify and kill a process. What are the steps? • Task 1: Redirecting and piping standard output Procedure 1. Obtain a list of files from the home directory, including the hidden files. Redirect the output to a file named Listing by using the ls -a > listing command. 2. Obtain a long list of files, including the hidden files, and append the output to the same file. 3. Use the cat listing | less command to view the file and pipe the output to less. 4. Use the cat command to view the file again. However, this time, pipe the output to lpr to print the file. 5. Redirect the output of ls to the special file /dev/null. What happens? It’s redirected to dev/null Why? It’s null. • Task 2: Putting tasks in the background and terminating the job Procedure 1. Use the tail –f command to view your listing file from the previous task. The –f option tells tail to follow changes; therefore, the file will continue to run this command until you cancel the command by pressing Ctrl+C. Put the file in the background using the tail -f listing & command. You may need to press Enter again to view the command prompt. 2. Put the process in the background and display the prompt again. Run the top command in the foreground. This will provide you a list of your top 20 processes by CPU usage. Put this list in the background and stop it by pressing...

Words: 780 - Pages: 4

Free Essay

I Donthave Anything to Upload

...1b) to what extent are things only good because God commands them? (10) To find out the extent to which things are only good because of God commanding them you would first have to decide whether an action or thing becomes good because of God commanding it or if it is good before. Other questions which should be examined include whether the things God has commanded you to do are actually ‘good’ and if the things God has said are wrong and immoral really are. Personally I believe that many things can be good even if God has not declared it to be so and this point has become increasingly obvious throughout time; one of the most renowned and obviously ridiculous examples of things that God has informed us is not ‘good’ is homosexuality. In my opinion this is the best example of why the answer to our question is a ‘very small extent’; God, Christianity and many other religions are absolutely against homosexuality with no exceptions at all taking a strictly deontological view on the matter. Despite the act you would think, not hurting anyone Leviticus 18:22 clearly states that this is an abomination and those who practice homosexuality should be put to death, yet the entire religion of Christianity is based upon love, love of oneself, love of your neighbour, and most importantly love of God. But why should the love of another man be considered evil? God has clearly commanded that humans should not be gay and that the act is wrong, evil, and most poignantly not ‘good’ but then sets...

Words: 901 - Pages: 4

Premium Essay


...1. Use the whatis command to determine the purpose of the ls command. whatis what? [will@localhost ~]$ whatis man man (1) - an interface to the on-line reference manuals man (7) - macros to format man pages man (1p) - display system documentation 2. Use the man program to find out what the -R option does when used with the date command. SYNOPSIS date [OPTION]... [+FORMAT] date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]] DESCRIPTION Display the current time in the given FORMAT, or set the system date. -r, --reference=FILE display the last modification time of FILE 3. Use the man program to determine what other commands you should also see in relation to the clear command SEE ALSO tput(1), terminfo(5) This describes ncurses version 5.9 (patch 20140323). 4. Use the cal command to determine on what day of the week you were born. will@localhost ~]$ cal 5 1975 5. Use the cal command to determine which year between 2005 and 2010 is a leap year. [will@localhost ~]$ cal 2 2008 February 2008 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 6. Clear the screen, and view the online manual to determine how to display today’s date in UTC. Clear date -u 7. Display the current UTC. Tue Feb 10 15:10:57 UTC 2015 8. Create a file called month containing the current month ...

Words: 334 - Pages: 2

Free Essay


..._______|6. Mi ---- con el médico es a las nueve y media de la mañana.|f. fiebre| _______|7. Me siento malo. Necesito esa ---.|g. descansar| _______|8. Una ---- alta es 104.5°.|h. la gripe| _______|9. No dormí mucho anoche. Necesito --- hoy.|i. cita| B. Fill in the chart using the steps of making an affirmative tú command.| infinitive|él, ella, usted present tense form |+ command|meaning| hablar|habla|habla|Speak.| tomar medicina | |toma|Take medicine.| descansar mucho|descansa| | | |lee| |Read more.| colgar el teléfono|cuelga| | | | |barre el suelo| | decir la verdad|------------| | | |------------|ve a la clase de inglés| | C. Fill in the chart using the steps of making a negative tú command. | infinitive|yo form |- command|meaning| hablar|hablo|No hables.|Don't speak.| |como| |Don't eat paper.| salir tarde|salgo| | | | |No llegues temprano.|Don't arrive early.| colgar el teléfono| |No cuelgues el teléfono. | | decir eso| | |Don't say that.| ir solo|------------| |Don't go alone.| estar nervioso|------------| | | explicar todo| | |Don't explain everything. | D. Here is some advice that a doctor might give. Put it in the correct command form. Ejemplo: no beber mucha sodaNo bebas mucha soda.1. dormir mucho2. beber mucho agua3. tomar las pastillas4. comer sopa de pollo5. hacer ejercicios6. no ser antipático7. no comer muchas grasas (fats)8. no fumar (smoke)9. no estar nervioso10. no tener mucho estrésE. You have been chosen to be the guide of an...

Words: 408 - Pages: 2

Free Essay

Huck Finn Essay add 500 gold, it would be entered as: player.additem 00000f 500 Targeting To target an object, open the console and click the object. Its name will appear about center screen. An item targeted in the console is also called a reference. A target may also be selected using the PRID command and the target's Reference ID. Short Code or Prefix Required Short code refers to a code having a short form that can be used interchangeably with the Long form. * ToggleFogOfWar is the long code form. * TFOW is the short code form. Prefix Required refers to a code needing a prefix to work as intended. * SetHealth <#> will set the max health of the target selected by clicking or the PRID command to <#>. * Player.SetHealth <#> will set your max health to <#>. Subpages Alchemy | Armor | Items | Food and Drinks Potions and Poisons Ingredients | Heavy Light Clothing Jewelry | Books Keys Miscellaneous Soul Gems | Weapons | Magic | Other | Arrows Blades Blunts Bows Staves | Spells Diseases Enchantments Perks Shouts Skills | Actor Values Batch Lists Characters Factions Locations Weather | Toggle commands Command | Effect | rm | Toggle Run Mode. Will switch between run mode and walking mode. Same function as <Caps Lock> key. | tg | Toggles grass | ts | Toggles display of skybox and fog. | TLL | Toggles LOD | TIM | Toggle Immortal Mode (Still take damage, health will never...

Words: 2661 - Pages: 11

Free Essay


...1. Command used, "whatis ls". The purpose of ls is to list directory contents 2. Command used, "man date". The -R option outputs RFC-2822 complaint date string when used with the date command. 3. Command used, "man clear". Other commands shown from this output in the text were tput and terminfo. 4. Command used, "cal 8 1991". I was born on Friday, August 2nd, 1991. 5. Commands used, "cal 2 20XX (XX being 06 through 15)". By looking for which years contained February 29th, I determined (confirmed) that 2008 and 2012 are both leap years. 6. Commands used, "clear" and "man date". Determined that option -u, --utc, and --universal for the date command will display todays date in UTC. 7. Command used, "date -u". As of right now, todays date and time as displayed from the ouput is Mon Jan 18 21:58:55 UTC 2010. 8. Commands used, "cat > month" and "cal 1 2010 >> month". I used "cat > month" to create a file called month and then " cal 1 2010 >> month" to add information to the existing month file with the current month. 9. Command used, "more month". This command displayed the contents of the month file created in Exercise 8, displaying January of 2010. 10. Commands used, "who -u >> users_info" and "more users_info". The "who -u >> users_info" command input information about idle time for users currently logged into into the file called users_info. The "more users_info" command displayed the contents of this file. 11. Command used, "more month users_info". This displayed the...

Words: 855 - Pages: 4

Premium Essay

Nt1210 Intro to Networking Lab 5.4

...(starting from node A), what command would you use to get this information? Give the command sequence you would enter at the command line to retrieve this information. I already have the IP Addresses for all the workstations a simple Ping command in CMD will work. Windows+R will bring up run command type CMD or go to start menu then accessories CMD. From CMD we would type Ping –a to retrieve the information we need. Exercise 5.4.2 What is the best (easiest and most efficient) command to determine whether all the hosts on the local-area network are reachable? You can assume that you are starting from computer A. List the command sequence(s) you would need to enter to test this functionality. Windows+R will bring up run command type CMD or go to start menu then accessories CMD. From CMD we would type Ping, Ping, and Ping, Ping, and Ping This would be a quick easier way but for a more complex way type FOR /L %i IN (1,1,254) DO ping -n 1 192.168.1.%i | FIND /i "Reply">>c:\ipaddresses.txt in CMD. exercise 5.4.3 Exercise 5.4.3 If your computer (node A) is unable to reach the Internet, what is the best way to determine where the error is occurring using command-line networking? Give the command sequence you would use to determine this. Ping Exercise 5.4.4 If your local machine (node A) is not connecting to any other hosts on the network, what two commands will give you information on whether...

Words: 344 - Pages: 2

Free Essay


...APPENDIX vi Commands |Insert and replace | |i |insert before cursor | |I |insert at beginning of line | |a |append after cursor | |A |append after end of line | |o |open blank line below cursor to insert | |O |open blank line above cursor to insert | |r |replace current character | |R |replace characters at cursor position | |C |change rest of line beginning at cursor position | |ESC |quit Text-input mode and return to vi-command mode | |Operators | |x |delete character(s)at cursor ...

Words: 363 - Pages: 2

Free Essay


...Singleton Description: The singleton pattern is a design pattern that ensures a class only has one instance, and provide a global point of access to it. Motivations: Single instance of a class to exist in the system Easily accessible Factory Description: The Factory Patterns are creational patterns which abstract the object instantiation process. They hide how objects are created and make the overall system independent of how its objects are created. Class creational patterns focus on the use of inheritance to decide the object to be instantiated in the Factory Pattern. Motivations: Let its related subclasses decide which class to instantiate but use the instance as a parent instance Used when the class does not know precisely which class of objects it must Class Diagram: Scenario Factory design pattern works as bridge between multiple classes. An example is using two databases of Oracle and SQL Server. Using SQL at first and it should be changed into Oracle in the future. Without a factory design pattern, all codes have to be modified, but with a factory design pattern, a little work is required. At first, the code should create a database factory according to the database type required. Then, use the factory creating SQL instances to develop the project. You do not need to know what is the type of the database factory and the detail of how it is implemented. When you want to change SQL server to Oracle, modify the implementation of database factory. No furthermore modifications...

Words: 742 - Pages: 3

Free Essay

Design Patterns

...Term paper On Design patterns Advanced topics in software engineering CSC 532 Submitted by:- Harpreet Singh Abstract:- Design patterns, a standard solution to problems in object oriented software engineering, are considered to be a well formed language to represent software design. Their benefits have been widely acknowledged by software professionals throughout the world. Design patterns can be classified according to multiple criteria the most common being the type of problem they solve. Till today many design patterns have been established and many more are being found as time passes. Patterns capture knowledge from various parts of software developing. Design patterns are helpful to the designers in a way that they represent the collective wisdom and experience of the community and their implementation leads to better quality software and also a novice designer does not find it difficult to understand the systems functionality. A very important advantage of design patterns is the fact that they speed up the development process by providing an almost ready-made solution that has been used earlier and proved to be efficient. Another advantage is that they allow for a generalized solution that does not depend on understanding a specific design problem from all its aspects, and thus ease reusing this solution. Apart from that they help the new developers to ignore traps and pitfalls which have earlier been learned by other developers by costly experience...

Words: 2632 - Pages: 11

Free Essay


... Title : Study any two patterns and SUBMIT a design pattern specification these in a standard format along with their UML diagrams. The specification must include Problem/ Issue, Audience/ Context, Forces, Solution, Discussion/ Consequences/ Implementation, Related Patterns, Example Instances, References. Theory: Introduction: Creational design patterns abstract the instantiation process.they help make a system independent of how its objects are created,composed & represented.a class creational pattern uses inheritanceto vary the class that’s intiated,where as creational pattern will delegate instantiation to another object.creational pattern become important as systems evolve to depend more on object composition than class that happens,emphasis shifts away from hard-coding a fixed set of behaviors toword defining a smaller set of fundamental behaviours that can be composedinto any no. of more complex onces.thus creating objects with perticular behaviour requires more than simply instantiating a class. Design patterns “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.” [Christopher Alexander] Design patterns capture the best practices of experienced object-oriented software developers. Design patterns are solutions to general...

Words: 1228 - Pages: 5