Skip to content

Design Patterns

A design pattern is a named solution to a recurring problem in a context. The name matters as much as the code: “I’d use a Strategy here” communicates a structure in three words. The danger is the opposite failure — applying patterns where a plain method would do, and calling it architecture.

Design patterns are vocabulary, not recipes. Creational patterns control how objects are made (Factory, Builder, Singleton). Structural patterns compose objects (Adapter, Decorator, Facade, Composite, Proxy). Behavioural patterns manage communication and responsibility (Strategy, Observer, Template Method, Command, Iterator, State). In Ruby many of them collapse into a block or a stdlib module, so use the pattern when the problem is genuinely there — variable behaviour, complex construction, an external interface you cannot change — not because a book listed it.

Factory moves object selection out of the caller, for when the concrete class depends on input or configuration. Builder handles many optional parameters that would otherwise become a long positional list — though Ruby keyword arguments replace it more often than not.

class Notifier
def self.for(channel)
case channel
when :email then EmailNotifier.new
when :sms then SmsNotifier.new
else raise ArgumentError, "unknown channel: #{channel}"
end
end
end

Singleton gives one instance, globally accessible. Ruby ships it in the standard library.

require "singleton"
class Config
include Singleton
attr_accessor :timeout
end
Config.instance.timeout = 5

Adapter wraps an incompatible interface so the rest of the code sees the one it expects: a StripeAdapter exposing charge(amount, token) over a client with different names.

Decorator adds behaviour without subclassing. Ruby’s SimpleDelegator and modules make it idiomatic:

require "delegate"
class Coffee
def cost = 3.0
def description = "coffee"
end
class WithMilk < SimpleDelegator
def cost = super + 0.5
def description = "#{super}, milk"
end
WithMilk.new(Coffee.new).cost # => 3.5

Facade presents one simple interface over a subsystem — ActiveRecord over SQL, connection pooling and type casting. Composite treats a tree of objects and a leaf uniformly (a File and a Directory both respond to size). Proxy stands in for another object to add access control, lazy loading or logging. Flyweight shares immutable state to save memory (interned strings).

Strategy swaps an algorithm behind a common interface. In Ruby a block or a callable usually beats a class hierarchy:

def apply(list, &strategy) = strategy.call(list)
apply(%w[ccc a bb]) { |l| l.sort_by(&:length) } # => ["a", "bb", "ccc"]

Observer notifies many subscribers when a subject changes; ActiveSupport::Notifications and Turbo broadcasts are observers. Template Method puts the skeleton in a base class and lets subclasses fill the steps — Ruby’s Comparable inverts it: implement <=> and it supplies the rest.

Command encapsulates a request as an object so it can be queued, logged or undone; Sidekiq job objects are commands. Iterator traverses without exposing internals — each and Enumerator are the built-in form. State models transitions as objects instead of a case on a status column; useful when the rules are complex, overkill for two states.

Patterns are indirection, and indirection costs: more files, more jumps, more concepts for the next reader. Do not introduce one when:

  • There is one implementation and no sign of a second. A PaymentStrategy interface with a single implementation is a guess about the future.
  • A block or lambda is enough. Strategy, Command and Template Method collapse into yield.
  • The language already provides it. Enumerable is Iterator, SimpleDelegator is Decorator.
  • The abstraction does not remove a real conditional. If the factory’s case just moves the case from the caller, nothing improved.
  • You cannot name the problem it solves. “It’s more testable” is not a problem statement.

Rule of thumb: introduce the pattern on the second real need, not the first imagined one.

  1. Which of these patterns does Ruby make redundant, and why?
  2. How would you test a class that uses the Singleton pattern?
  3. What is the difference between Adapter, Decorator and Proxy — all three wrap an object?
  4. When would you replace a Strategy hierarchy with a lambda?
  5. How do Rails conventions already encode several of these patterns?
  • Pattern names as a substitute for design. “I used Repository and CQRS” says nothing about whether the code is correct.
  • Factory that is a case in disguise. You moved the coupling, not removed it.
  • Singleton for convenience. Global state in a nicer suit; it breaks test isolation.
  • Decorator chains that obscure the call stack. Five nested wrappers are harder to debug.
  • Confusing Proxy with Decorator. Proxy controls access; Decorator adds behaviour.