Hello and happy Friday!
Today I’ll be talking a bit about my journey so far into understanding the adapter and decorator patterns. Based upon the wikipedia definitions of the decorator pattern and adapter pattern, I was at a loss in understanding the differences between them.
I found a key difference between a Decorator (aka smart proxy) and an Adapter is that a Decorator pattern is preferred when we would like to add functionality to an object, but not by extending the object’s type. The Adapter pattern adds no additional functionality to the adaptee class, and while both patterns introduce a level of indirection between a client class and the class it uses, the Adapter pattern is creational, whereas the Decorator pattern is a structural design pattern.
The Adapter Pattern
Using the Adapter pattern adapts the subject (also called the adaptee) to a different interface, leaving us with an ability for an object to be placed into a collection of slightly different types. It also increases the readability of our code by exposing only relevant methods to the client.
In our code base, an Adapter is thin. It shouldn’t add much code to the adaptee class, besides calling the adaptee’s methods.
Here are some resources I’ve found to help me understand and implement this in my current project lunch_panoply.
The Adapter Pattern by: MikeAbyss
Adapter Design Pattern by: Derek Banas
A metaphor and literal explanation by: The Cal Poly CSC Dept.
The Decorator Pattern
The Decorator pattern allows behavior to be added to an existing object at runtime. This is considered to be more flexible than inheritance and simplifies our code because we are adding functionality using many simple classes. So rather than rewriting old code we can just extend our features with new code.
To better explain this pattern, I’ve listed a few resources I’m still learning to understand:
- Quick Review: Decorator Pattern in Ruby by: Fred(Erick)
- Decorators in Ruby by: Krešimir Bojčić
- Evaluating Alternative Decorator Implementations in Ruby by: Dan Croak via @thoughtbot
- And a Decorator Design Pattern video by: Derek Banas
I’ll be re-visiting these resources over this weekend with the goal of being able to sense when I would need to use these patterns and also how to properly implement them in Ruby.
To help with my overall understanding, I’ll be going to this video talk by Sandi Metz titled SOLID Object-Oriented Design.
And here’s one more video that explains Sandi’s book and the benefits of each chapter of her book.