Creational Patterns Lab
Retrieval Prompts
- Describe Factory Method in one sentence. Give one scenario in which it is the right answer.
- Describe Abstract Factory in one sentence. What guarantee does it protect that Factory Method does not?
- Describe Builder in one sentence. Name two invariants a Builder's
build()method should enforce. - Describe Prototype in one sentence. When is it better than a constructor?
- 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:
- "We have a class with one concrete subclass, so we introduced a Factory Method to stay flexible."
- "Our
Configis a Singleton because we only ever have one configuration per run." - "Our
OrderBuildervalidates each field as it is set." - "An Abstract Factory is just a Factory Method with more methods."
- "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
Reporterwith a template methodrenderReport(data)that callscreateRenderer() - two subclasses,
HtmlReporterandTextReporter, 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:
UIFactoryinterface withcreateButtonandcreateScrollBar- 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'impliesbody == null) - a call site that constructs both a trivial and a complex request for easy comparison
Reflection
After implementing the pattern:
- Rewrite the same solution without the pattern, using the simplest shape your language supports.
- Compare the two. Pick one with a written reason.
- 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