From 51f5d352c69a4775a9cee70702a5b066623cd57e Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Mon, 11 Nov 2024 10:28:35 +0100 Subject: [PATCH] added strategy example --- .../simple_strategy/ConcreteStrategyA.java | 8 ++++++++ .../simple_strategy/ConcreteStrategyB.java | 8 ++++++++ src/learn/simple_strategy/Context.java | 17 +++++++++++++++++ src/learn/simple_strategy/Main.java | 11 +++++++++++ src/learn/simple_strategy/Strategy.java | 5 +++++ 5 files changed, 49 insertions(+) create mode 100644 src/learn/simple_strategy/ConcreteStrategyA.java create mode 100644 src/learn/simple_strategy/ConcreteStrategyB.java create mode 100644 src/learn/simple_strategy/Context.java create mode 100644 src/learn/simple_strategy/Main.java create mode 100644 src/learn/simple_strategy/Strategy.java diff --git a/src/learn/simple_strategy/ConcreteStrategyA.java b/src/learn/simple_strategy/ConcreteStrategyA.java new file mode 100644 index 0000000..552b561 --- /dev/null +++ b/src/learn/simple_strategy/ConcreteStrategyA.java @@ -0,0 +1,8 @@ +package learn.simple_strategy; + +public class ConcreteStrategyA implements Strategy { + @Override + public void algorithm() { + System.out.println("nice strategy A"); + } +} diff --git a/src/learn/simple_strategy/ConcreteStrategyB.java b/src/learn/simple_strategy/ConcreteStrategyB.java new file mode 100644 index 0000000..1b8ca92 --- /dev/null +++ b/src/learn/simple_strategy/ConcreteStrategyB.java @@ -0,0 +1,8 @@ +package learn.simple_strategy; + +public class ConcreteStrategyB implements Strategy { + @Override + public void algorithm() { + System.out.println("nice strategy B"); + } +} diff --git a/src/learn/simple_strategy/Context.java b/src/learn/simple_strategy/Context.java new file mode 100644 index 0000000..ad97da8 --- /dev/null +++ b/src/learn/simple_strategy/Context.java @@ -0,0 +1,17 @@ +package learn.simple_strategy; + +public class Context { + private Strategy currentStrategy; + + public Context(Strategy currentStrategy) { + this.currentStrategy = currentStrategy; + } + + public void setCurrentStrategy(Strategy currentStrategy) { + this.currentStrategy = currentStrategy; + } + + public void doSomeJob() { + currentStrategy.algorithm(); + } +} diff --git a/src/learn/simple_strategy/Main.java b/src/learn/simple_strategy/Main.java new file mode 100644 index 0000000..8054d80 --- /dev/null +++ b/src/learn/simple_strategy/Main.java @@ -0,0 +1,11 @@ +package learn.simple_strategy; + +public class Main { + public static void main(String[] args) { + Context context = new Context(new ConcreteStrategyB()); + + context.doSomeJob(); + context.setCurrentStrategy(new ConcreteStrategyA()); + context.doSomeJob(); + } +} diff --git a/src/learn/simple_strategy/Strategy.java b/src/learn/simple_strategy/Strategy.java new file mode 100644 index 0000000..7d2efb3 --- /dev/null +++ b/src/learn/simple_strategy/Strategy.java @@ -0,0 +1,5 @@ +package learn.simple_strategy; + +public interface Strategy { + void algorithm(); +}