THE COMMAND PATTERN
The Chain of Responsibility forwards requests along a chain of
classes, but the Command pattern forwards a request only to a specific
module. It encloses a request for a specific action inside an object and gives it
a known public interface. It lets you give the client the ability to make
requests without knowing anything about the actual action that will be
performed, and allows you to change that action without affecting the client
program in any way.
Motivation
When you build a Java user interface, you provide menu items,
buttons, and checkboxes and so forth to allow the user to tell the program
what to do. When a user selects one of these controls, the program receives an
ActionEvent, which it must trap by subclassing, the actionPerformed event.
Let’s suppose we build a very simple program that allows you to select the
menu items File | Open and File | Exit, and click on a button marked Red
which turns the background of the window red. This program is shown
below.
The program consists of the File Menu object with the mnuOpen and
mnuExit MenuItems added to it. It also contains one button called btnRed. A
click on any of these causes an actionPerformed event that we can trap with
the following code:
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if(obj == mnuOpen)
fileOpen(); //open file
if (obj == mnuExit)
exitClicked(); //exit from program
if (obj == btnRed)
redClicked(); //turn red
}
The three private methods this method calls are just
private void exitClicked() {
System.exit(0);
}
//—————————————–
private void fileOpen() {
FileDialog fDlg = new FileDialog(this, "Open a file",
FileDialog.LOAD);
fDlg.show();
}
//—————————————–
private void redClicked() {
p.setBackground(Color.red);
}
Now, as long as there are only a few menu items and buttons, this
approach works fine, but when you have dozens of menu items and several
buttons, the actionPerformed code can get pretty unwieldy. In addition, this
really seems a little inelegant, since we’d really hope that in an objectoriented
language like Java, we could avoid a long series of if statements to
identify the selected object. Instead, we’d like to find a way to have each
object receive its commands directly.
The Command Pattern
One way to assure that every object receives its own commands
directly is to use the Command object approach. A Command object always
has an Execute() method that is called when an action occurs on that object.
Most simply, a Command object implements at least the following interface:
public interface Command {
public void Execute();
}
The objective of using this interface is to reduce the actionPerformed
method to:
public void actionPerformed(ActionEvent e) {
Command cmd = (Command)e.getSource();
cmd.Execute();
}
Then we can provide an Execute method for each object which
carries out the desired action, thus keeping the knowledge of what to do
inside the object where it belongs, instead of having another part of the
program make these decisions.
One important purpose of the Command pattern is to keep the
program and user interface objects completely separate from the actions that
they initiate. In other words, these program objects should be completely
separate from each other and should not have to know how other objects
work. The user interface receives a command and tells a Command object to
carry out whatever duties it has been instructed to do. The UI does not and
should not need to know what tasks will be executed.
The Command object can also be used when you need to tell the
program to execute the command when the resources are available rather than
immediately. In such cases, you are queuing commands to be executed later.
Finally, you can use Command objects to remember operations so that you
can support Undo requests.
Building Command Objects
There are several ways to go about building Command objects for a
program like this and each has some advantages. We’ll start with the simplest
one: deriving new classes from the MenuItem and Button classes and
implementing the Command interface in each. Here are examples of
extensions to the Button and Menu classes for our simple program:
class btnRedCommand extends Button
implements Command {
public btnRedCommand(String caption) {
super(caption); //initialize the button
}
public void Execute() {
p.setBackground(Color.red);
}
}
//——————————————
class fileExitCommand extends MenuItem
implements Command {
public fileExitCommand(String caption) {
super(caption); //initialize the Menu
}
public void Execute() {
System.exit(0);
}
}
This certainly lets us simplify the calls made in the actionPerformed
method, but it does require that we create and instantiate a new class for each
action we want to execute.
mnuOpen.addActionListener(new fileOpen());
mnuExit.addActionListener(new fileExit());
btnRed.addActionListener(new btnRed());
We can circumvent most of the problem of passing needed
parameters to these classes by making them inner classes. This makes the
Panel and Frame objects available directly.
However, interior classes are not such a good idea as commands
proliferate, since any of them that access any other UI components have to
remain inside the main class. This clutters up the code for this main class with
a lot of confusing little inner classes.
Of course, if we are willing to pass the needed parameters to these
classes, they can be independent. Here we pass in the Frame object and a
Panel object:
mnuOpen = new fileOpenCommand("Open…", this);
mnuFile.add(mnuOpen);
mnuExit = new fileExitCommand("Exit");
mnuFile.add(mnuExit);
p = new Panel();
add(p);
btnRed = new btnRedCommand("Red", p);
p.add(btnRed);
In this second case, our menu and button command classes can then be
external to the main class, and even stored in separate files if we prefer.
The Command Pattern in Java
But there are still a couple of more ways to approach this. If you give
every control its own actionListener class, you are in effect creating
individual command objects for each of them. And, in fact, this is really what
the designers of the Java 1.1 event model had in mind. We have become
accustomed to using these multiple if test routines because they occur in most
simple example texts (like mine) even if they are not the best way to catch
these events.
To implement this approach, we create little classes each of which
implements the ActionListener interface:
class btnRed implements ActionListener {
public void actionPerformed(ActionEvent e) {
p.setBackground(Color.red);
}
}
//————————————-
class fileExit implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
}
and register them as listeners in the usual way.
mnuOpen.addActionListener(new fileOpen());
mnuExit.addActionListener(new fileExit());
btnRed.addActionListener(new btnRed());
Here we have made these inner classes, but they also could be external with
arguments passed in, as we did above.
Consequences of the Command Pattern
The main disadvantage of the Command pattern is a proliferation of
little classes that either clutters up the main class if they are inner or clutters
up the program namespace if they are outer classes.
Now even in the case where we put all of our actionPerformed events
in a single basket, we usually call little private methods to carry out the actual
function. It turns out that these private methods are just about as long as our
little inner classes, so there is frequently little difference in complexity
between inner and outer class approaches.
Anonymous Inner Classes
We can reduce the clutter of our name space by creating unnamed
inner classes by declaring an instance of a class on the spot where we need it.
For example, we could create our Red button and the class for manipulating
the background all at once
btnRed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
p.setBackground(Color.red);
}
} );
number of run-time classes since the compiler generates a class file even for
these unnamed classes.
In fact, there is very little difference in the compiled code size among
these various methods, as shown in Table 1, once you create classes in any
form at all.
Providing Undo
Another of the main reasons for using Command design patterns is
that they provide a convenient way to store and execute an Undo function.
Each command object can remember what it just did and restore that state
when requested to do so if the computational and memory requirements are
not too overwhelming.
Risk Of Downs Syndrome Older Mothers Sexy Mature Lesbains Muffdiving Video Femme Mature Fist Fucking Cock Craving Mature Mature Ass Milf Mature Milf Xxx Personals Mature Fucking Bottle – Mature Mom Forced To Suck Rodney Older Women , Benefits Of Growingt Older Profile !!! http://canberragames.net/forums/viewtopic.php?f=28&t=4529 – Nude Older Women Closeup
Grannies Wearing Pantyhose Older Ladies Panty Thumbnails Mature Tutor Anal Mature Milf Rack Regina Hairy Mature Mature Bowling Balls Older Padded Home Bar Sets – Loss Of Appetite In Older Canines Hot Busty Bbw Mature 02 , Mature Tutors !!! http://elforodejona.solamentesoluciones.net/viewtopic.php?f=32&t=58480 – Older Model Vtech Replacement Phones
Breast-feeding Older Kids Granny Midget Mature Family Guy Bryan Naked Granny Suck Boy Mature Madam Paris Mature Miniskirt Older Nudes Doggy Style – Mature Training Small Breast Mature Pussy , Photos Classic Busty Mature Woman !!! http://elforodejona.solamentesoluciones.net/viewtopic.php?f=35&t=58458 – Mature Bangs
Mature Women Oiled Family In Older Generation In Bangladesh Mature Chubby Lesbians Jpg Mature Sexy Plumpers Olg Granny Creampie 12 Grannies Forced To Fuck Older Matures In Nylons – Grannies Panty Pee Starter For Older Cub Cadet , Buying Mature Palm Trees !!! http://elforodejona.solamentesoluciones.net/viewtopic.php?f=16&t=58466 – Bound Grannies
http://wwwsitedoingp.cn/thumb/mature/mature15.jpg
Jobs For People 55 And Older Mature Ebony Bbw Older Palm Mature Biography Older Model Kitchenaid Dishwashers Wh3 Series Online Movies And 18 Or Older Milf And Mature Password – Mature Fitness Awards Usa Older Black Ladys Xxx , Mature Older Blonde !!! http://forum.hougar.com/viewtopic.php?f=26&t=67874 – Mature Lesbian Seduce Girls Porn
Aunt Judy Mature Older Women Gall Bladder Removal In Older Patients Meet Gay Older Men Myspace I Like Older Guys Mature Lesbian Free Stories Archives Russian Older Woman Mature Youngboys – Mature Korean Blowjob Super Granny Crack , Granny Sanger !!! http://www.forum.keeblers-trot.com/phpbb3/viewtopic.php?f=6&t=64086 – Mature Women Taking Their Clothes Off
Granny Shuffle Nude Weomen Eighteen Or Older Mature Eats Mans Ass Mature Porn Mom Son Healthcare Services By Older Adults Sexy Hot Matures Mature Hairy Women Videos – Older In Pantyhose Grannies And Fatties Porn , Mature Latina Wifes !!! http://mex.monashclubs.org/forums/index.php?topic=33143.new#new – Polka Dot Mature
Non Commercial Mature Naked Wife Club Older Version No Trax Rock And Roll Granny Older Spanish Women Asian Women Older Men Adobe Older Version Download Granny Spreads Pussy – Older Than Dirt Quiz Mature Women Sucking And Fucking , His Older Brother !!! http://forum.hougar.com/viewtopic.php?f=16&t=67871 – Mature Women In Tight Jeans Tgp
http://wwwsitedoingp.cn/thumb/mature/mature26.jpg
Openoffice Older Version Win98 Mature Skanks Grannies Jerkoffs Mature Wallpapers Granny Pictrues Guia Older Babes Mature Woman Seducing Young Male – Mature Thin Slipper Crochet Granny Squares , Mature Asian Blowjob !!! http://forum.seoserver.ru/viewtopic.php?f=14&t=172541 – Big Mature Movies Tgp
Mature Nude Women Amatuers Hot Mature Homegrown Older Bbw Nudes Older Moms Nipple Sex Clips Mature Sex Amateurs Fat Older Pussy Hardcore Grannies Thumbna – Young Mature Sex Scared Video Mature British Milf , Mature Women Slips Panties !!! http://forum.seoserver.ru/viewtopic.php?f=9&t=172516 – Mature Victor
Mature Mom Fucking Black Cock Trashy Clothes For Mature Women Grannys Giving Blowjobs Mature Nudist Pix Giant Mature Boobs Granny Big Tits Vids Mature Women Screaming – Mature Tits Tease Free Roswell Fanfic Izzy Older Brother , Pretty Mature Wom En !!! http://www.druglycats.ru/forum/viewtopic.php?p=276185#276185 – Over Fifty Mature
Younger Girls Fucking Older Men Backpage Escorts Mature Cheap Plastic Pants For Older Kids Smokin Hot Mature Women Pics Older Housewives Photography Older Mao Inhibitor New York Granny Thumbs – Sexy Mature Teacher Handjob Videos Dizziness In Older People , Secretary Older Penis !!! http://forum.seoserver.ru/viewtopic.php?f=21&t=172557 – Dating Sites And Personals Older Women
http://wwwsitedoingp.cn/thumb/mature/mature20.jpg
Rash On Older Tattoo Mature Funny Video Clips Granny Naturalists Mature Woman Legs Mature Blonde Teacher Classy Mature Pussy Mature Leah – Sites Matures Lawyer Client Mature Fucking , Gifts For The Older Man !!! http://medwaste.ru/talks/index.php?action=vthread&forum=1&topic=240&page=277#msg232186 – Mature Black Fat Pussy
Hot Grannies With Big Tits Mature Young Sex 10 Hairy Granny Blows Slammed Romantic Bondage Mature Women Grannies T Rkish Sex Mexican Mature Porn Granny Sucking Boy 2 – Femme Mature Porno Mature Ebony Photo , Mature Black Actors !!! http://forum.huaxiaworld.com/phpBB/viewtopic.php?f=2&t=23565 – 50 Mature Sex Movies
Mature Group Sex Parties Mature Hookers Fuck Mature Free Panty Stoking Pics Granny School Uniform Grannies Masturbate Mature Greek Video Mature Women With Teens – Adult Mature Dating Site Mature Woman Perth , Mature Women Squirt !!! http://www.gaybikers.org/viewtopic.php?f=13&t=20457 – Older Huge Tit Brunette
Nudist And Photo And Mature Mature Swingers Sex Movies Granny’S Place And Tennessee Black Hair Styles For Older Sexy Matures Tgp Black Hose Mature Outdoor Pantie Mature Hunnies – Hard Rammed Granny Hbo Mature Videos Online , Hot Granny Fucked !!! http://www.nunat.net/forum/viewtopic.php?f=2&t=19366 – Lampshade Older Style
http://wwwsitedoingp.cn/thumb/mature/mature18.jpg