Command - Sam647254/Programetoj GitHub Wiki
Java
/** The Command interface */
interface Command {
void execute();
}
/** The Invoker class */
class Switch {
private final HashMap<String, Command> commandMap = new HashMap<>();
public void register(String commandName, Command command) {
commandMap.put(commandName, command);
}
public void execute(String commandName) {
Command command = commandMap.get(commandName);
if (command == null) {
throw new IllegalStateException("no command registered for " + commandName);
}
command.execute();
}
}
/** The Receiver class */
class Light {
public void turnOn() {
System.out.println("The light is on");
}
public void turnOff() {
System.out.println("The light is off");
}
}
public class CommandDemo {
public static void main(final String[] arguments) {
Light lamp = new Light();
Command switchOn = lamp::turnOn;
Command switchOff = lamp::turnOff;
Switch mySwitch = new Switch();
mySwitch.register("on", switchOn);
mySwitch.register("off", switchOff);
mySwitch.execute("on");
mySwitch.execute("off");
}
}
TypeScript
interface Light {
turnOn: () => void;
turnOff: () => void;
}
interface Switch {
register: (commandName: string, command: () => void) => void;
execute: (commandName: string) => void;
}
function createSwitch(): Switch {
return {
commands: new Map<string, () => void>(),
register(commandName: string, command: () => void) {
this.commands.put(commandName, command);
},
execute(commandName: string) {
this.commands.get(commandName)();
},
};
}
function createLight(): Light {
return {
turnOn() { console.log("The light is on."); },
turnOff() { console.log("The light is off."); },
};
}
// main
const lamp = createLight();
const switch = createSwitch();
switch.register("γγ―γΌγΉγ€γγγͺγ³", () => {
lamp.turnOn();
});
switch.register("off", () => {
lamp.turnOff();
});
switch.execute("γγ―γΌγΉγ€γγγͺγ³");
switch.execute("off");