Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 134 ยท Object-Oriented Ruby

Design Patterns

Learn six classic design patterns in idiomatic Ruby - Observer, Strategy, Decorator, Builder, State and Command - using blocks, modules and duck typing, with runnable code.

A design pattern is a named, reusable solution to a problem that keeps appearing. The famous catalogue was written for languages where you need classes and interfaces for everything. In Ruby, blocks, duck typing, modules and open objects often shrink a pattern to a few lines, so the same idea looks different (and lighter) than in a Java textbook. Knowing the names still helps: they let you say "this is a strategy" in a code review and be understood.

This lesson shows six patterns that come up constantly in Ruby code: Observer, Strategy, Decorator, Builder, State and Command. For each one you get the problem, an idiomatic implementation and a note on when to avoid it. It assumes you know Blocks, Modules and Mixins and the ideas in Design Principles in Ruby.

Observer: tell interested parties

Problem: when something happens in one object, several others need to react, without the first one knowing who they are. Think of a stock price that updates a chart, an alert and a log.

Ruby's standard library has an Observable module, but it became a bundled gem in Ruby 3.4+ (a real project would need gem "observer" in its Gemfile), and a callback list is only a dozen lines. Blocks make the subscribers trivial:

Ruby Observer with blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The thermostat holds a list of callables and calls each when the value changes. Returning the listener from subscribe gives callers a handle to unsubscribe later. Remember to unsubscribe long-lived listeners, or they keep objects alive (a memory leak in disguise). Avoid when one direct method call would do; a hidden web of observers is hard to follow.

Strategy: swap the algorithm

Problem: one task can be done in several interchangeable ways, chosen at runtime (sort by price or by name, shipping by weight or by flat rate). In Ruby a strategy is anything that responds to a common method, very often a lambda or a method object.

Ruby Strategy with lambdas and objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Cart does not care how shipping is computed; it just calls the strategy. The same approach powers sort_by, map and every method that takes a block. Avoid building a class hierarchy when a lambda says it in one line.

Decorator: wrap to add behavior

Problem: add behavior (logging, caching, formatting) to an object without changing its class and without a subclass for every combination. A decorator wraps another object and exposes the same interface. SimpleDelegator from the standard library forwards everything it does not define (see Forwardable and Delegation); here is a hand-written one that stays visible:

Ruby Stacking decorators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Each wrapper has the same two methods as Coffee, so they stack in any order. Logged shows the general version: a dynamic proxy built with method_missing that records calls and forwards them (always pair method_missing with respond_to_missing?, see method_missing and respond_to_missing?). Avoid deep stacks: many layers make stack traces and debugging harder. For wrapping a method of one class, prepend is often simpler (The Ruby Object Model).

Builder: construct complex objects step by step

Problem: an object needs many optional parts, and a constructor with ten parameters is unreadable. A builder collects settings first and produces the final (often immutable) object last. In Ruby the builder is frequently a block that is evaluated on a builder object.

Ruby A builder with a block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Method chaining (each setter returns self) and the block form with instance_eval are the two common Ruby styles; the second becomes a mini language, see Building DSLs. Validation lives in build, so you can never get an invalid Pizza. Avoid a builder when keyword arguments with defaults (Pizza.new(size: :large)) are clear enough.

State: behavior that depends on a mode

Problem: an object behaves differently depending on its state (an order that can be draft, paid or shipped), and if status == ... checks multiply in every method. Move each state's behavior into its own object.

Ruby State objects for an order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Order forwards each action to its current state object, and states replace themselves. Adding a new state touches one class, not every method. For small state machines a symbol plus a table of allowed transitions (a hash) is often enough, and Pattern Matching can express transitions neatly. Avoid the full pattern for two states.

Command: turn an action into an object

Problem: you want to queue, log, undo or replay actions. A command packages an action and the data it needs. In Ruby that can be a small class with execute (and undo), or just a lambda.

Ruby Commands with undo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Because each action is an object, History can store them and run undo in reverse order; the final undo on an empty history returns nil thanks to the safe navigation operator &.. The same shape powers job queues, macro recording and transaction logs. Avoid it when you never need to store, undo or defer the call.

Choosing and combining patterns

Pattern Reach for it when Ruby shortcut
Observer many parties react to one event array of blocks
Strategy interchangeable algorithms lambda or any object with call
Decorator add behavior around an object wrapper, SimpleDelegator, prepend
Builder many optional parts, final validation chaining or block DSL
State behavior differs by mode state objects or a transition hash
Command queue, log or undo actions object with execute / undo

Patterns are tools, not goals. If the simple version of the code is clear, leave it. When a method keeps growing branches or a class keeps being edited for unrelated reasons, that is the moment a pattern earns its place. Singletons and the standard Observable module are covered in Observable, Singleton and Standard Patterns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which pattern lets many objects react to an event without the sender knowing them?

    The subject keeps a list of listeners and notifies each one, without depending on who they are.
  2. 2. In Ruby, the lightest way to implement the Strategy pattern is often:

    Strategies only need a shared method. A lambda or tiny object with call satisfies that.
  3. 3. Why does a decorator stack (Sugar.new(Milk.new(Coffee.new))) work in any order?

    A decorator has the same methods as the wrapped object, so it can be wrapped again.
  4. 4. What problem does the State pattern remove?

    Each state object holds its own behavior, so the context just delegates to the current state.
  5. 5. What does a Command object let you do that a plain method call does not?

    Because the action is an object with its own data, it can be kept in a list, replayed, serialized or reversed.

Summary

  • Patterns are named solutions; in Ruby blocks, lambdas, modules and duck typing make most of them very small.
  • Observer: keep a list of callables and notify them; unsubscribe when done.
  • Strategy: pass an object or lambda that responds to call instead of branching on a type.
  • Decorator: wrap an object with the same interface, or use prepend / SimpleDelegator.
  • Builder: collect options with chaining or a block, validate in build, return an immutable result.
  • State and Command: move per-state behavior or whole actions into objects so they can be swapped, queued and undone.

Next: Introduction to Metaprogramming