Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.luv2code.designpatterns.behavioral.command;

import java.util.List;

/**
* Role: ConcreteCommand (Macro)
*
* Groups a list of commands into a single named scene.
* Execute runs all commands in order.
* Undo runs them in reverse order.
*/
public class MacroCommand implements SmartHomeCommand {

private String name;
private List<SmartHomeCommand> commands;

public MacroCommand(String name, List<SmartHomeCommand> commands) {
this.name = name;
this.commands = commands;
}

@Override
public void execute() {
System.out.println("[Macro] Running: " + name);

for (SmartHomeCommand command : commands) {
command.execute();
}
}

@Override
public void undo() {
// go in reverse order
System.out.println("[Macro] Running: " + name);

for (int i = commands.size() -1; i >= 0; i--) {
commands.get(i).undo();
}
}

@Override
public String getDescription() {
return "Macro: " + name;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.luv2code.designpatterns.behavioral.command;

import java.util.List;

/**
* Role: Client
*
Expand All @@ -18,8 +20,34 @@ static void main() {

System.out.println("\n--- Demo 3: Pet Food Demo ---");
runPetFoodDemo();

System.out.println("\n--- Demo 4: Macro Command Demo ---");
runMacroCommandDemo();
}

private static void runMacroCommandDemo() {

Light officeLight = new Light("Office");
Light bedroomLight = new Light("Bedroom");
Thermostat thermostat = new Thermostat(16);
RemoteControl remoteControl = new RemoteControl();

// Build a "Good Morning" scene - one button press runs all three commands
SmartHomeCommand goodMorningCommand = new MacroCommand("Good Morning",
List.of(new LightOnCommand(officeLight),
new LightOnCommand(bedroomLight),
new ThermostatSetCommand(thermostat, 21)
));

remoteControl.pressButton(goodMorningCommand);

System.out.println("\n-- Undoing the entire scene with one press --");
remoteControl.pressUndo();
}




private static void runPetFoodDemo() {

PetFoodDispenser petFoodDispenser = new PetFoodDispenser("Max");
Expand Down