From 3a2484a123c38570d985992867441171eab02de1 Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Sun, 13 Oct 2024 18:22:53 +0200 Subject: [PATCH] added command pattern example --- src/learn/simple_command/Command.java | 5 +++++ src/learn/simple_command/ConcreteCommand.java | 14 ++++++++++++++ src/learn/simple_command/Invoker.java | 13 +++++++++++++ src/learn/simple_command/Main.java | 12 ++++++++++++ src/learn/simple_command/Receiver.java | 7 +++++++ 5 files changed, 51 insertions(+) create mode 100644 src/learn/simple_command/Command.java create mode 100644 src/learn/simple_command/ConcreteCommand.java create mode 100644 src/learn/simple_command/Invoker.java create mode 100644 src/learn/simple_command/Main.java create mode 100644 src/learn/simple_command/Receiver.java diff --git a/src/learn/simple_command/Command.java b/src/learn/simple_command/Command.java new file mode 100644 index 0000000..14dc34a --- /dev/null +++ b/src/learn/simple_command/Command.java @@ -0,0 +1,5 @@ +package learn.simple_command; + +public interface Command { + void execute(); +} diff --git a/src/learn/simple_command/ConcreteCommand.java b/src/learn/simple_command/ConcreteCommand.java new file mode 100644 index 0000000..096d079 --- /dev/null +++ b/src/learn/simple_command/ConcreteCommand.java @@ -0,0 +1,14 @@ +package learn.simple_command; + +public class ConcreteCommand implements Command { + private Receiver receiver; + + public ConcreteCommand(Receiver receiver) { + this.receiver = receiver; + } + + @Override + public void execute() { + receiver.action(); + } +} diff --git a/src/learn/simple_command/Invoker.java b/src/learn/simple_command/Invoker.java new file mode 100644 index 0000000..b63e39c --- /dev/null +++ b/src/learn/simple_command/Invoker.java @@ -0,0 +1,13 @@ +package learn.simple_command; + +public class Invoker { + private Command slot; + + public void setSlot(Command slot) { + this.slot = slot; + } + + public void buttonWasPushed() { + slot.execute(); + } +} diff --git a/src/learn/simple_command/Main.java b/src/learn/simple_command/Main.java new file mode 100644 index 0000000..3f3c933 --- /dev/null +++ b/src/learn/simple_command/Main.java @@ -0,0 +1,12 @@ +package learn.simple_command; + +public class Main { + public static void main(String[] args) { + Invoker invoker = new Invoker(); + Receiver receiver = new Receiver(); + Command command = new ConcreteCommand(receiver); + invoker.setSlot(command); + + invoker.buttonWasPushed(); + } +} diff --git a/src/learn/simple_command/Receiver.java b/src/learn/simple_command/Receiver.java new file mode 100644 index 0000000..99cd199 --- /dev/null +++ b/src/learn/simple_command/Receiver.java @@ -0,0 +1,7 @@ +package learn.simple_command; + +public class Receiver { + public void action() { + System.out.println("Do my action"); + } +}