So far we’ve dealt with design smells and played with the Duck factory. Which is a great segue into our next topic, Design Patterns, one of which is the Factory Pattern. Design patterns allow us to look at our code, usually as the need for changes arise and utlize the benefits of a design pattern. With our Duck Factory exercises this is where we began. We created duck objects and added them to a pond. As the number of types of ducks changed so did their behaviors. Does a rubber duck quack? Can a cement duck float? Does decoy duck fly? Our initial Factory design pattern worked fine until we our duck types changed and it became evident that the design pattern needed to evolve. Out first iteration took the factory design pattern and migrated to an Abstract Factory pattern. Now our ducks could inherit behaviors from interfaces. But should a decoy duck be inheriting quack behaviors? The Abstract Factory design pattern is really just a transitional pattern to the Strategy Pattern. As we moved our code around it became clear that we were making things a little more complicated than they needed to be. We were starting to introduce some needless design smells. The advantage of the Strategy Pattern is it favors encapsulation. The “Strategy” is to define a set of algorithms, encapsulate each one and make them interchangeable. This allows the algorithms to vary independently from the clients that use them. In the case of our Duck Factory and the ducks (and duck sub-classes) use the encapsulated behaviors (and sub-behaviors) to fly, quack, squeak, and in the case of cement duck sink. We covered 3 other design patterns and next week I’ll touch on those. Until then happy coding! #CS@Worcester #CS343
From the blog Michael Duquette by Michael Duquette and used with permission of the author. All other rights reserved by the author.