Part 4 of 6 · 1 min read
The simple factory
One place that knows the classes.
The simplest cure is a class whose only job is to make objects. HF calls it a simple factory.
class NotifierFactory {
static Notifier create(String kind) {
switch (kind) {
case "EMAIL": return new Email();
case "SMS": return new Sms();
default: throw new IllegalArgumentException("unknown kind: " + kind);
}
}
}
NotifierFactory.create("SMS").send("hi") returns "sms:hi". Asking for "FAX" throws an exception with the message "unknown kind: FAX". The business code now names only the Notifier interface and the factory. A new channel is added in one place.
HF is clear that the simple factory is not a real design pattern. It calls it more of a programming idiom, and a warm-up for the heavier patterns. HF also notes that defining it as a static method is common, with the cost that it cannot be subclassed or replaced in tests.
The simple factory still has the switch, so it breaks the open-closed principle (Level 2, module 2). That is acceptable. All the switching now lives in one small class, instead of being spread over the program. When the list of kinds grows large, replace the switch with a map from the kind to a creation function, or move to the pattern in section 4.
Simple factory
A simple factory is a class with a method that creates objects of related types, so that callers do not name the concrete classes.
Example: NotifierFactory.create("SMS").
Common mistake
Calling every factory "the factory pattern". The simple factory, the static factory method and the Factory Method pattern are three different things.
Check yourself:
1. What does create("FAX") do?
2. Why does HF say a simple factory is not a pattern?
3. Where does the switch live now?