Reading the strategy pattern of notes in head first design pattern

Design a different duck call and fly behavior:

Abstract class for flight:

public interface FlyBehavior {
    public void fly();
}

It's called the abstract class of behavior:

public interface QuackBehavior {
    public void quack();
}

To achieve multiple flights:

// Can fly
public class FlyWithWings implements FlyBehavior {
    public void fly() {
        System.out.println("I'm flying!!");
    }
}

// No fly
public class FlyNoWay implements FlyBehavior {
    public void fly() {
        System.out.println("I can't fly");
    }
}

To implement multiple behavior instances:

public class Quack implements QuackBehavior {
    public void quack() {
        System.out.println("Quack");
    }
}

public class MuteQuack implements QuackBehavior {
    public void quack() {
        System.out.println("<< Silence >>");
    }
}

public class Squeak implements QuackBehavior {
    public void quack() {
        System.out.println("Squeak");
    }
}

Duck's parent class:

public abstract class Duck {
    FlyBehavior flyBehavior;
    QuackBehavior quackBehavior;

    public Duck() {}

    public abstract void display();

    public void performFly() { // Delegate to behavior
        flyBehavior.fly();
    }

    public void performQuack() { // Delegate to behavior
        quackBehavior.quack();
    }

    public void swim() {
        System.out.println("All ducks float, even decoys!");
    }
}

Start creating a duck:

public class MallardDuck extends Duck {
    // It's not easy to extend the behavior in the constructor. Use set to dynamically create / change ducks with different behaviors
    public MallardDuck() {
        quackBehavior = new Quack();
        flyBehavior = new FlyWithWings();
    }

    public void display() {
        System.out.println("I'm a real Mallard duck");
    }

    public void setFlyBehavior(FlyBehavior fb) {
        flyBehavior = fb;
    }

    public void setQuackBehavior(QuackBehavior qb) {
        quackBehavior = qb;
    }
}

Let the ducks fly and shout

public class MiniDuckSimulator {
    public static void main(String[] args) {
        Duck mallard = new MallardDuck();

        mallard.performQuack(); // Delegate
        mallard.performFly();

        // Change duck behavior at will
        mallard.setFlyBehavior(new FlyNoWay());
        mallard.setQuackBehavior(new MuteQuack());

        mallard.performQuack(); // Delegate
        mallard.performFly();
    }
}

Strategy pattern: defines the algorithm family (that is, the behavior group of duck's flying and calling) and encapsulates them separately so that they can replace each other. This pattern makes the algorithm change independent of the customers using the algorithm.

Posted on Fri, 10 Jan 2020 12:48:53 -0500 by TheIrishThug