Saturday, March 18, 2017

Design Patterns

Humans are great at seeing patterns. When a programmer solves a lot of problems, he starts to see solutions that seem generally applicable to a wide category of problems. When those problems are design problems (how to manage the objects and the relationship between objects), those solutions are known as "design patterns".

There are different types of patterns:
  • Creational
    • ways to manage the creation of objects
  • Behavioral 
    • ways to manage the communication of objects
  • Structural 
    • ways to organize objects
A common structural pattern is known as the decorator or wrapper pattern. You use it by wrapping an object with another object that has the same interface which then modifies the behavior of the inner object. You're basically creating an onion :)

Decorator pattern in the wild

If you've ever build a rails application, you've probably run into situations where the controller is filled with code responsible for formatting your data for presentation. There's a library called draper that allows you to write decorator models that wrap your models with functions that will do the formatting, which removes an additional responsibility from your controllers.

Why not just use inheritance?

Less flexible. With decorators, you can decorate your objects at run time by wrapping them with other objects. With inheritance, you lose that flexibility.


No comments:

Post a Comment