In this blog we begin a new series as summary to Head Fist Design Pattern.
Now we are at Chapter 1: Intro to Design Patterns. This chapter introduces strategy pattern cleverly with an example of simDuck app.
Intro
Suppose you are working for a company that simulates duck behaviors. For this purpose, the current code base maintains an abstract class Duck
, and many subclasses like MallardDuck
, RedHeadDuck
, RubberDuck
. Previously, the duck could only swim, display itself. However, now the company wants to add behaviors to ducks, names fly
and quack
behaviors.
This seems easy to do, you add two abstract methods fly
, quack
to the Duck
abstract class, and go ahead to every subclass to implement these two methods ... But this is not DRY (don't repeat yourself) as many ducks could fly, and fly similarly. So if you implement fly to every class, you are copying paste many times. This would be error-prone and difficult to maintain in the future.
How should we solve this problem elegantly? Probably we could abstract interface FlyBehavior
and QuackBehavior
, then gives concrete implementations like FlyWithWings
, FlyNoWays
, Quack
, MuteQuack
, Squeak
etc. For the abstract class Duck
, we define its behavior as interface
/ supertype
, with the real / concrete behavior being defined at runtime/subclasses.
And that is exactly the Strategy Pattern.
Formal Definition
The Strategy Pattern defines a family of algorithms, encapsulates each other, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Design Principles
Identify the aspects of your application that vary and separate them from what stays the same.
Program to an interface, not an implementation.
Favor composition over inheritance.
OO basics
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
Graphs
The big picture using Strategy Pattern:
Top comments (0)