From the course: Programming Foundations: Design Patterns

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Exploring the strategy pattern

Exploring the strategy pattern

From the course: Programming Foundations: Design Patterns

Start my 1-month free trial

Exploring the strategy pattern

- [Instructor] We had an initial design for a duck simulator that used inheritance, but we quickly ran into problems with this design. We were having to change a lot of code in the subclasses when we added new ducks and we were duplicating code. We fixed the design by pulling out the flying and quacking behaviors and composing those behaviors with the ducks, that way each duck could use the behaviors that is right for that duck. The class design that we created for the duck simulator is an implementation of the strategy pattern. Let's take a look at the class diagram for the strategy pattern. We have an inheritance hierarchy that defines the type of the objects that need a behavior and we have a HASA relationship between those objects and their behaviors. These behaviors can be anything. Any algorithm that an object might need to perform. By moving these algorithms out from the main inheritance hierarchy, we get the…

Contents