课程: Programming Foundations: Design Patterns

今天就学习课程吧!

今天就开通帐号,24,100 门业界名师课程任您挑!

Exploring the strategy pattern

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…

内容