Subscribe to PHP Freaks RSS

StarTutorial.com: Understanding Design Patterns - Decorator

syndicated from www.phpdeveloper.org on June 25, 2018

The StarTutorial site has posted the latest in their series of tutorials introducing common design patterns and their use in PHP. In this latest tutorial they cover the decorator pattern.

[The Decorator pattern] attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

The tutorial illustrates the pattern using a base Coffee class (black coffee by default). It talks about how you could extend this class for every other kind of coffee but that gets complex quickly. Instead, they show the use of the Decorator pattern to augment the instance of the base Coffee class with decorators to add sugar and cream to the coffee. This not only makes it easier to maintain but allows for a more flexible system, adding only what you need when you need it.