Head First Design Patterns -- charpter 1
It start with a simple SimUDuck app
But now, we need the ducks to fly
Opps!The RubberDuck fly in the Sky
We can solve the bus in the way
If we add a new class like DecoyDuck
How about an interface ?
What would happened to this design?
How can we solve this problem?
Animal animal = new Dog();
animal.MakeSound();
animal = new Cat();
animal.MakeSound();
Implementing the Duck Behavior
How about this design?
Ok, It’s time to solve the problem
We’ll add two instance variables to the Duck class.
implement performQuack():
public class Duck {
QuackBehavior quackBehavior;
// more
public void performQuack() {
quackBehavior.quack();
}
}
Set the flyBehavior and quackBehavior instance variables.
public class MallardDuck extends Duck {
public MallardDuck() {
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
}
Finish the Main Function
public class MiniDuckApp {
public static void main (String[] args) {
Duck mallard = new MallardDuck();
mallard.performQuack();
mallard.performFly();
}
}
Congratulations on your first pattern!
The Strategy Pattern
Defines a family of algorithms, encapsulates each one, and makes them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.
Thanks