Creational patterns
The five creational patterns of the GoF catalogue: Singleton, Factory Method, Abstract Factory, Builder and Prototype. Their intent, participants, a code example and their limits.
- 25 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Understand
A few cards from the deck
Singleton: what is it?
Show the answer
Creational pattern that guarantees a class has a single instance and provides a global access point to it.
The constructor is private and the class keeps its only instance in a static field. The global access point is also its flaw: it hides a dependency and gets in the way of tests.
This Singleton lets two instances be created, even in a program without concurrency. Why?
```java
public class Config {
private static Config instance;
public Config() { }
public static Config getInstance() {
if (instance == null) {
instance = new Config();
}
return instance;
}
}`- The constructor is public:
new Config()creates a second instance - The
instancefield isstatic: it is overwritten on every call togetInstance getInstanceis static: each calling class gets its own copy- The condition
instance == nullcreates an object on every call
Show the answer
The constructor is public:
new Config()creates a second instanceNothing stops other code from calling the public constructor: uniqueness is no longer guaranteed. It must be declared
private. The static field exists only once for the whole class, the staticgetInstancereturns that same object to every caller, and the condition only creates the object on the first call.- The constructor is public:
For a class to have only one instance, its constructor is … and it keeps the instance in a … field.
Show the answer
For a class to have only one instance, its constructor is private and it keeps the instance in a static field.
With a public constructor, any code could call
newand create a second instance: the uniqueness guarantee would collapse.Factory Method: what is it?
Show the answer
Creational pattern that defines a creation method in a parent class and lets the subclasses decide which concrete class to instantiate.
The creator's code calls the factory method and only knows the product's type, never its concrete class. Adding a product means adding a subclass.
With an Abstract Factory, why can't the application show a light button next to a dark menu?
- Each widget checks, when created, the theme of the widgets already made
- All its widgets come from the same concrete factory, chosen only once
- Light and dark widgets inherit from the same concrete class
- The client tests the current theme before every call to
new
Show the answer
All its widgets come from the same concrete factory, chosen only once
The client never calls
newon a widget: it asks a single factory, light or dark, forcreateButton()andcreateMenu(). The family's consistency comes from that one choice, not from scattered checks.