Presentation is loading. Please wait.

Presentation is loading. Please wait.

Command Pattern Encapsulation Invocation. One size fits all.

Similar presentations


Presentation on theme: "Command Pattern Encapsulation Invocation. One size fits all."— Presentation transcript:

1 Command Pattern Encapsulation Invocation

2 One size fits all

3 Vender Classes

4 Intro to Command Pattern

5 Interaction in detail

6 Encapsulation An order Slip encapsulates a request to prepare a meal. An order Slip encapsulates a request to prepare a meal. The waitress's job is to take order Slips and invoke the orderUp() method on them. The waitress's job is to take order Slips and invoke the orderUp() method on them. The Cook has the knowledge required to prepare the meal. The Cook has the knowledge required to prepare the meal.

7 API interface??

8 From Dinner to Command Pattern

9 Our first command object public interface Command { public void execute(); } Implementing Command to turn light on public class LightOnCommand implements Command { public LigthOnCommand(Light light) { this.light = light; } public void execute(){ light.on(); } } Light on() off()

10 Using Command object public class SimpleRemoteControl { Command slot; public SimpleRemoteControl() { } public void setCommand(Command command) { slot = command; } public void buttonWasPresses() { slot.execute(); }

11 Creating a simple test public class RemoteControlTest { public static void main(String[] args) { SimpleRemoteControl remote = new SimpleRemoteControl(); Light light = new Light(); GarageDoor garageDoor = new GarageDoor(); LightOnCommand lightOn = new LightOnCommand(light); GarageDoorOpenCommand garageOpen = new GarageDoorOpenCommand(garageDoor); remote.setCommand(lightOn); remote.buttonWasPressed(); remote.setCommand(garageOpen); remote.buttonWasPressed(); } }

12 Command Pattern Defined The Command Pattern encapsulates a request as an object; thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.

13

14

15

16 public class RemoteControl { Command[] onCommands; Command[] offCommands; public RemoteControl() { onCommands = new Command[7]; offCommands = new Command[7]; Command noCommand = new NoCommand(); for (int i = 0; i < 7; i++) { onCommands[i] = noCommand; offCommands[i] = noCommand;}} public void setCommand(int slot, Command onCommand, Command offCommand) { onCommands[slot] = onCommand; offCommands[slot] = offCommand;} public void onButtonWasPushed(int slot) { onCommands[slot].execute();} public void offButtonWasPushed(int slot) { offCommands[slot].execute();} }}

17


Download ppt "Command Pattern Encapsulation Invocation. One size fits all."

Similar presentations


Ads by Google