Skip to content

Instantly share code, notes, and snippets.

@uxdxdev
Last active January 27, 2023 16:47
Show Gist options
  • Save uxdxdev/92a340194ac7fdd75dc49da42b3b7242 to your computer and use it in GitHub Desktop.
Save uxdxdev/92a340194ac7fdd75dc49da42b3b7242 to your computer and use it in GitHub Desktop.
// Receiver
class Entity {
String name;
public Entity(String name){
this.name = name;
}
public void jump(){
System.out.println(name + " Jump");
}
public void fire(){
System.out.println(name + " Fire");
}
}
// Command interface
interface ICommand {
public void execute(Entity entity);
}
// Concrete command
class JumpCommand implements ICommand {
public void execute(Entity entity){
entity.jump();
}
}
class FireCommand implements ICommand {
public void execute(Entity entity){
entity.fire();
}
}
// Invoker
class InputHandler {
static boolean xPressed = false;
static boolean yPressed = false;
// Commands
ICommand jumpCommand = new JumpCommand();
ICommand fireCommand = new FireCommand();
public ICommand handleInput(){
if(xPressed) {
xPressed = false;
return jumpCommand;
}
else if(yPressed) {
yPressed = false;
return fireCommand;
}
// nothing pressed
return null;
}
}
// Client
public class Game {
public static void main(String args[]) {
// Receivers
Entity player = new Entity("Player");
Entity enemy = new Entity("Enemy");
InputHandler inputHanler = new InputHandler(); // Invoker
InputHandler.xPressed = true; // press x button
ICommand command = inputHanler.handleInput();
if(command != null){
command.execute(player);
command.execute(enemy);
command.execute(enemy);
}
InputHandler.yPressed = true; // press y button
command = inputHanler.handleInput();
if(command != null){
command.execute(player);
command.execute(enemy);
command.execute(enemy);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment