feat(hw-03): implement Strategy pattern
This commit is contained in:
@@ -8,6 +8,7 @@ import org.example.builder.*;
|
||||
import org.example.chain.*;
|
||||
import org.example.decorator.*;
|
||||
import org.example.proxy.*;
|
||||
import org.example.strategy.*;
|
||||
|
||||
public class App {
|
||||
public static void main(String[] args) {
|
||||
@@ -16,10 +17,16 @@ public class App {
|
||||
|
||||
private static void run() {
|
||||
checkAdapterPattern();
|
||||
|
||||
checkBuilderPattern();
|
||||
|
||||
checkChainPattern();
|
||||
|
||||
checkDecoratorPattern();
|
||||
|
||||
checkProxyPattern();
|
||||
|
||||
checkStrategyPattern();
|
||||
}
|
||||
|
||||
private static void checkAdapterPattern() {
|
||||
@@ -57,4 +64,16 @@ public class App {
|
||||
|
||||
proxy.execute();
|
||||
}
|
||||
|
||||
private static void checkStrategyPattern() {
|
||||
Context context = new Context(new ConcreteStrategyA());
|
||||
|
||||
boolean crayfishWhistled = true; // Если рак на горе свистнул
|
||||
|
||||
if (crayfishWhistled) {
|
||||
context.setStrategy(new ConcreteStrategyB());
|
||||
}
|
||||
|
||||
context.executeStrategy();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package org.example.strategy;
|
||||
|
||||
/** Concrete Strategy A */
|
||||
public class ConcreteStrategyA implements Strategy {
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
System.out.println("ConcreteStrategyA выполняет операцию");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package org.example.strategy;
|
||||
|
||||
/** Concrete Strategy B */
|
||||
public class ConcreteStrategyB implements Strategy {
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
System.out.println("ConcreteStrategyB выполняет операцию");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.example.strategy;
|
||||
|
||||
/** Context */
|
||||
public class Context {
|
||||
|
||||
public Context(Strategy strategy) {
|
||||
this.strategy = strategy;
|
||||
}
|
||||
|
||||
public void setStrategy(Strategy strategy) {
|
||||
this.strategy = strategy;
|
||||
}
|
||||
|
||||
public void executeStrategy() {
|
||||
strategy.execute();
|
||||
}
|
||||
|
||||
private Strategy strategy;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package org.example.strategy;
|
||||
|
||||
/** Strategy */
|
||||
public interface Strategy {
|
||||
void execute();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user