Strategy
Used when you need to dynamically
change an object behavior at run time.
This pattern
separates behavior from super and subclasses.
It allows you to
eliminate code duplication.
class App {
public static void main(String[] args) {
Master m = new Master();
m.name = "Socrate";
m.speak();
Pupil p = new Pupil();
p.name = "Alcibiades";
p.speak();
}
}
class Master implements Speak {
public String name;
public void speak() {
System.out.println(name + ": I can raise questions ...");
}
}
class Pupil implements Speak {
public String name;
public void speak() {
System.out.println(name + ": I can answer!");
}
}
interface Speak {
public void speak();
}
With Strategy Pattern we use an
instance variable (composition technique).
It allows us to change the capabilities of objects
at run time!
class Alcibiades {
public static void main(String[] args) {
Master m = new Master("Socrate");
m.type = new AskCapable();
m.speak();
Pupil p = new Pupil("Alcibiades");
p.type = new AskIncapable();
p.speak();
p.type = new AskCapable();
p.speak();
}
}
class Master extends Human {
public Master(String n) {
name = n;
}
}
class Pupil extends Human {
public Pupil(String n) {
name = n;
}
}
abstract class Human {
String name;
Speak type;
public void speak() {
System.out.print(name + ": ");
type.speak();
}
}
class AskCapable implements Speak {
public void speak() {
System.out.println("I can raise questions ...");
}
}
class AskIncapable implements Speak {
public void speak() {
System.out.println("I can answer!");
}
}
interface Speak {
public void speak();
}
class TheRings {
public static void main(String[] args) {
Wizard w1 = new Wizard("Saruman");
Wizard w2 = new Wizard("Gandalf");
Hobbit h1 = new Hobbit("Frodo");
w1.type = new Fly();
w2.type = new Ride();
h1.type = new Run();
int level = 1;
while (level <= 3) {
System.out.println("\nLevel " + level);
if (level == 2) {
h1.type = new Disappear();
}
if (level == 3) {
w2.type = new Fly();
w1.type = new Run();
}
w1.display(); w1.move();
w2.display(); w2.move();
h1.display(); h1.move();
level = level + 1;
}
}
}
class Wizard extends Item {
String name;
public Wizard(String n) {
name = n;
}
public void display() {
System.out.print(name);
}
}
class Hobbit extends Item {
String name;
public Hobbit(String n) {
name = n;
}
public void display() {
System.out.print(name);
}
}
abstract class Item {
Move type;
public void move() {
type.move();
}
abstract void display();
}
interface Move {
public void move();
}
class Fly implements Move {
public void move() {
System.out.print(" (Fly) ");
}
}
class Ride implements Move {
public void move() {
System.out.print(" (Ride) ");
}
}
class Run implements Move {
public void move() {
System.out.print(" (Run) ");
}
}
class Disappear implements Move {
public void move() {
System.out.print(" (Disappear) ");
}
}
Strategy v2.0 Alcibiades can't ask
Strategy v2.2 Alcibiades is wiser now, he can ask