File tree Expand file tree Collapse file tree 2 files changed +73
-0
lines changed
section-04-behavioral-design-patterns/16-command/src/main/java/com/luv2code/designpatterns/behavioral/command Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .luv2code .designpatterns .behavioral .command ;
2+
3+ import java .util .List ;
4+
5+ /**
6+ * Role: ConcreteCommand (Macro)
7+ *
8+ * Groups a list of commands into a single named scene.
9+ * Execute runs all commands in order.
10+ * Undo runs them in reverse order.
11+ */
12+ public class MacroCommand implements SmartHomeCommand {
13+
14+ private String name ;
15+ private List <SmartHomeCommand > commands ;
16+
17+ public MacroCommand (String name , List <SmartHomeCommand > commands ) {
18+ this .name = name ;
19+ this .commands = commands ;
20+ }
21+
22+ @ Override
23+ public void execute () {
24+ System .out .println ("[Macro] Running: " + name );
25+
26+ for (SmartHomeCommand command : commands ) {
27+ command .execute ();
28+ }
29+ }
30+
31+ @ Override
32+ public void undo () {
33+ // go in reverse order
34+ System .out .println ("[Macro] Running: " + name );
35+
36+ for (int i = commands .size () -1 ; i >= 0 ; i --) {
37+ commands .get (i ).undo ();
38+ }
39+ }
40+
41+ @ Override
42+ public String getDescription () {
43+ return "Macro: " + name ;
44+ }
45+ }
Original file line number Diff line number Diff line change 11package com .luv2code .designpatterns .behavioral .command ;
22
3+ import java .util .List ;
4+
35/**
46 * Role: Client
57 *
@@ -18,8 +20,34 @@ static void main() {
1820
1921 System .out .println ("\n --- Demo 3: Pet Food Demo ---" );
2022 runPetFoodDemo ();
23+
24+ System .out .println ("\n --- Demo 4: Macro Command Demo ---" );
25+ runMacroCommandDemo ();
2126 }
2227
28+ private static void runMacroCommandDemo () {
29+
30+ Light officeLight = new Light ("Office" );
31+ Light bedroomLight = new Light ("Bedroom" );
32+ Thermostat thermostat = new Thermostat (16 );
33+ RemoteControl remoteControl = new RemoteControl ();
34+
35+ // Build a "Good Morning" scene - one button press runs all three commands
36+ SmartHomeCommand goodMorningCommand = new MacroCommand ("Good Morning" ,
37+ List .of (new LightOnCommand (officeLight ),
38+ new LightOnCommand (bedroomLight ),
39+ new ThermostatSetCommand (thermostat , 21 )
40+ ));
41+
42+ remoteControl .pressButton (goodMorningCommand );
43+
44+ System .out .println ("\n -- Undoing the entire scene with one press --" );
45+ remoteControl .pressUndo ();
46+ }
47+
48+
49+
50+
2351 private static void runPetFoodDemo () {
2452
2553 PetFoodDispenser petFoodDispenser = new PetFoodDispenser ("Max" );
You can’t perform that action at this time.
0 commit comments