Friday, February 01, 2019

Remembering Design Patterns

There are 23 design patterns described in the classic GoF book. I have found myself an easier way to remember them:

First, I divide them into three categories:

  • Creational Patterns
  • Structural Patterns
  • Behavior Patterns

Creational Patterns

Their purposes are to parameterize systems by the classes of objects they create.

  • Create a group of objects: Abstract Factory
  • Create a single object. This can further be categorized by how clients use this pattern.
    • Use by composition:
      • Create by clone: Prototype
      • Create once: Singleton
      • Create complex object: Builder
    • Use by inheritance: Factory Template

Structural Patterns

They are used to compose larger structures from smaller ones.

  • One interface (Don’t change or add other interfaces)
    • Group together calls: Composite
    • Intercept calls: Proxy
    • Add state or behavior to calls: Decorator
  • Two/Many interfaces
    • Adapt interface A to B: Adapter
    • Two interfaces at both sides of a bridge can evolve independently: Bridge
    • A single interface to hide the complexity of a number of interfaces: Facade
  • Structural & Creational pattern: Flyweight, to cache static states as singletons, and passing dynamic states when calling

Behavioral Patterns

They try to encapsulate algorithms or allocate responsibilities.

  • encapsulate general algorithm by composition: Strategy
  • encapsulate general algorithm by inheritance: Template Method
  • encapsulate iteration algorithm: Iterator
  • encapsulate state based algorithms: State
  • encapsulate snapshot algorithm: Memento
  • encapsulate event notification: Observer
  • encapsulate nodes (e.g. AST nodes) visit algorithms: Visitor
  • encapsulate Abstract Syntax Tree parser algorithm: Interpretor
  • decouple interaction between related peer classes: Mediator
  • encapsulate how I was called
    • Command, implement Command interface and submit to an Executor, the executor will call me later.
    • Chain of responsibility, implement Handler interface and chain into an existing list of handlers. Upstream Handler will call me, and I have to call downstream handler.