bangerska nutka na początek i tak:
public interface IRunnerStrategy {
int nextStep(int currentStep);
}
do tego jakieś strategie przykładowo:
import org.springframework.stereotype.Component;
@Component
public class RunFast implements IRunnerStrategy {
@Override
public int nextStep(int currentStep) {
return currentStep + 5;
}
}
import org.springframework.stereotype.Component;
@Component
//@Primary - jezeli w Runnerze chce @Autowired
public class Walk implements IRunnerStrategy {
@Override
public int nextStep(int currentStep) {
return currentStep + 1;
}
}
Runner przyjmujący te strategie ( walk - domyślna):
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Runner {
@Value("0")
private int currentStep;
@Resource(name = "walk")
private IRunnerStrategy runnerStrategy;
public void nextStep() {
currentStep += runnerStrategy.nextStep(currentStep);
}
public int getCurrentStep() {
return currentStep;
}
public void setRunnerStrategy(IRunnerStrategy runnerStrategy) {
this.runnerStrategy = runnerStrategy;
}
}
przykładowy obiekt korzystający z Runnera, któremu zmienia strategie
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class Example {
@Autowired
private Runner runner;
@Resource(name = "walk")
private IRunnerStrategy walk;
@Resource(name = "runFast")
private IRunnerStrategy runFast;
//itd... tak musze ze wszystkimi strategiami eh ;.
public void start() {
System.out.println(runner.getCurrentStep());
runner.nextStep();
System.out.println(runner.getCurrentStep());
runner.setRunnerStrategy(runFast); //ZMIANA STRATEGII !!
runner.nextStep();
System.out.println(runner.getCurrentStep());
}
}
Wcześniej ustawianie strategii było np. new runFast()
teraz mam jako beany. Działa, ale czy to prawidłowe podejście (skoro mogę korzystać z Springa) ;] ? To przykład hipotetyczny, ale odzwierciedlający mój rzeczywisty problem.