added strategy example

This commit is contained in:
Louis Heredero 2024-11-11 10:28:35 +01:00
parent 7c614b0c5c
commit 51f5d352c6
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
5 changed files with 49 additions and 0 deletions

View File

@ -0,0 +1,8 @@
package learn.simple_strategy;
public class ConcreteStrategyA implements Strategy {
@Override
public void algorithm() {
System.out.println("nice strategy A");
}
}

View File

@ -0,0 +1,8 @@
package learn.simple_strategy;
public class ConcreteStrategyB implements Strategy {
@Override
public void algorithm() {
System.out.println("nice strategy B");
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,5 @@
package learn.simple_strategy;
public interface Strategy {
void algorithm();
}