Skip to main content

Creational Patterns Lab

Retrieval Prompts

  1. Describe Factory Method in one sentence. Give one scenario in which it is the right answer.
  2. Describe Abstract Factory in one sentence. What guarantee does it protect that Factory Method does not?
  3. Describe Builder in one sentence. Name two invariants a Builder's build() method should enforce.
  4. Describe Prototype in one sentence. When is it better than a constructor?
  5. Describe Singleton in one sentence. Give one case in which "we only need one" is not a valid reason to use it.

Compare and Distinguish

Separate these pairs clearly. Write one or two sentences for each:

  • Factory Method vs Abstract Factory
  • Abstract Factory vs Builder
  • Builder vs telescoping constructors
  • Singleton vs dependency-injected single instance
  • Prototype vs deep copy

Common Mistake Check

For each statement, identify the error:

  1. "We have a class with one concrete subclass, so we introduced a Factory Method to stay flexible."
  2. "Our Config is a Singleton because we only ever have one configuration per run."
  3. "Our OrderBuilder validates each field as it is set."
  4. "An Abstract Factory is just a Factory Method with more methods."
  5. "Prototype means deepCopy()."

Mini Application

Pick one and implement it end-to-end in your working language:

Application A -- Factory Method

Build a small Reporter framework:

  • abstract Reporter with a template method renderReport(data) that calls createRenderer()
  • two subclasses, HtmlReporter and TextReporter, that pick concrete renderers
  • one test that proves the template method itself does not change between subclasses

Application B -- Abstract Factory

Build a cross-platform UI factory:

  • UIFactory interface with createButton and createScrollBar
  • two concrete factories for two families (Desktop, Mobile)
  • a client function that builds a small screen and never checks the family

Application C -- Builder

Build an HttpRequest Builder (same shape as the concept page) with:

  • at least five settable fields, at least two of which are optional with defaults
  • one invariant enforced only in build() (e.g., method == 'GET' implies body == null)
  • a call site that constructs both a trivial and a complex request for easy comparison

Reflection

After implementing the pattern:

  1. Rewrite the same solution without the pattern, using the simplest shape your language supports.
  2. Compare the two. Pick one with a written reason.
  3. Tag the reason with one of: genuine variation, readability, testability, premature, cargo-cult.

Evidence Check

This page is complete only if you can:

  • explain which force each creational pattern relieves
  • name at least one case where the pattern is wrong for the problem
  • produce a working implementation you could show in a review