Java Tutorial/Design Pattern/Strategy Pattern
Версия от 17:44, 31 мая 2010; (обсуждение)
Action with the Strategy Pattern
public class MainClass {
public static void main(String[] args) {
Jet jet = new Jet();
jet.setGoAlgorithm(new DriveEngine());
jet.go();
jet.setGoAlgorithm(new FlyFastEngine());
jet.go();
jet.setGoAlgorithm(new DriveEngine());
jet.go();
}
}
abstract class Vehicle {
Engine goa = null;
public Vehicle() {
}
void setGoAlgorithm(Engine goa) {
this.goa = goa;
}
public void go() {
this.goa.go();
}
}
class Jet extends Vehicle {
public Jet() {
}
}
interface Engine {
public void go();
}
class FlyingFastEngine implements Engine {
public void go() {
System.out.println("Now I"m flying fast.");
}
}
class DriveEngine implements Engine {
public void go() {
System.out.println("Now I"m driving.");
}
}
class FlyFastEngine implements Engine {
public void go() {
System.out.println("Now I"m flying fast.");
}
}
Strategy: choosing the algorithm at run-time
interface Find {
double[] algorithm(double[] line);
}
class FindMethodA implements Find {
public double[] algorithm(double[] line) {
return new double[] { 1 };
}
}
class FindMethodB implements Find {
public double[] algorithm(double[] line) {
return new double[] { 2 };
}
}
class FindMethodC implements Find {
public double[] algorithm(double[] line) {
return new double[] { 3 };
}
}
class FindMethodD implements Find {
public double[] algorithm(double[] line) {
return new double[] { 4 };
}
}
class MySolver {
private Find strategy;
public MySolver(Find strat) {
strategy = strat;
}
double[] get(double[] line) {
return strategy.algorithm(line);
}
void changeAlgorithm(Find newAlgorithm) {
strategy = newAlgorithm;
}
}
public class StrategyPattern {
public static void main(String args[]) {
MySolver solver = new MySolver(new FindMethodA());
double[] line = { 1.0, 2.0, 1.0, 2.0, -1.0, 3.0, 4.0, 5.0, 4.0 };
solver.get(line);
solver.changeAlgorithm(new FindMethodC());
solver.get(line);
}
}