Action with the Strategy Pattern : Strategy Pattern « Design Pattern « Java Tutorial






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.");
  }
}








34.18.Strategy Pattern
34.18.1.Strategy: choosing the algorithm at run-time
34.18.2.Action with the Strategy Pattern