Factory: one place decides what to make
After this: Write a factory that turns a channel name into a notifier, and say what changes when a new channel arrives.
On this page · 7 sections · 4 checks
In lesson 2 the navigator was handed a route object, and the code outside made it with DriveRoute()new DriveRoute(). But often the program does not know in advance which class it needs. It only has a word.
An online shop tells customers when an order ships. Each customer picks how in their settings, and the shop stores the choice as a word: "email", "sms" or "push". The shop sends messages from many places: the order page, the delivery service, the refund desk. Each of them has the word and needs an object that can send. Where should the word become an object?
The problem with an if in every place
If each place writes its own if over the three words, the same choice is copied into every place. When the shop adds WhatsApp, someone must find and edit all of them. Miss one, and that part of the shop cannot send WhatsApp messages.
One place decides
The idea: put the choice in one method. Every place that sends asks that method for a sender, gives it the word, and gets back an object it can call send on. Only that method knows which class goes with which word.
A method or class whose job is to create the right object for you is called a . Here it is a class, NotifierFactory, with one method, create(channel).
create is a : you call it on the class name, NotifierFactory.create("sms"), without making a factory object first. Python marks it with @staticmethod and Java with the word static. In a class diagram a static method is underlined.
Step through the diagram. Look at which classes have arrows to SmsNotifier and its two neighbours.
Press Run it to build the diagram one step at a time.
- classes
- 0
- relations
- 0
The code
class EmailNotifier: def send(self, to, text): return f"EMAIL to {to}: {text}"
class SmsNotifier: def send(self, to, text): return f"SMS to {to}: {text}"
class PushNotifier: def send(self, to, text): return f"PUSH to {to}: {text}"
class NotifierFactory: @staticmethod def create(channel): if channel == "email": return EmailNotifier() if channel == "sms": return SmsNotifier() if channel == "push": return PushNotifier() raise ValueError("unknown channel: " + channel)
for ch in ["email", "sms", "push"]: notifier = NotifierFactory.create(ch) print(notifier.send("Ana", "order shipped"))try: NotifierFactory.create("fax")except ValueError as e: print("error:", e)EMAIL to Ana: order shipped SMS to Ana: order shipped PUSH to Ana: order shipped error: unknown channel: fax
import java.util.List;
interface Notifier { String send(String to, String text);}
class EmailNotifier implements Notifier { public String send(String to, String text) { return "EMAIL to " + to + ": " + text; }}
class SmsNotifier implements Notifier { public String send(String to, String text) { return "SMS to " + to + ": " + text; }}
class PushNotifier implements Notifier { public String send(String to, String text) { return "PUSH to " + to + ": " + text; }}
class NotifierFactory { static Notifier create(String channel) { if (channel.equals("email")) { return new EmailNotifier(); } if (channel.equals("sms")) { return new SmsNotifier(); } if (channel.equals("push")) { return new PushNotifier(); } throw new IllegalArgumentException("unknown channel: " + channel); }}
public class Main { public static void main(String[] args) { for (String ch : List.of("email", "sms", "push")) { Notifier notifier = NotifierFactory.create(ch); System.out.println(notifier.send("Ana", "order shipped")); } try { NotifierFactory.create("fax"); } catch (IllegalArgumentException e) { System.out.println("error: " + e.getMessage()); } }}EMAIL to Ana: order shipped SMS to Ana: order shipped PUSH to Ana: order shipped error: unknown channel: fax
Walk through it:
- The three notifier classes each have
send(to, text)and return their own line. In Java they implement the interfaceNotifier; in Python any object withsendwill do. createchecks the word, branch by branch, and returns a new object of the matching class.- A word with no branch reaches the last line, which raises a ValueErrorthrows an IllegalArgumentException with the text
unknown channel: fax. - The loop at the bottom stands for the places that send. For each word it asks the factory for a notifier and calls
send. It never namesEmailNotifier,SmsNotifierorPushNotifier.
The if is still there, but now there is only one copy of it. When WhatsApp arrives, you write one class and add one branch to create. Nothing that sends changes.
One call, step by step
The sequence diagram follows create("sms") and then a send. Notice the second arrow: it is the factory making a new object, so the SmsNotifier box appears at that height, not at the top.
Press Run it to send the messages one at a time.
- messages
- 0
- The client calls
create("sms")on the factory. - The factory makes a new
SmsNotifier. - It returns that object to the client.
- The client calls
send("Ana", "order shipped")on it, and gets backSMS to Ana: order shipped.
Run it
Add a WhatsAppNotifier whose send returns WHATSAPP to and the rest, add a branch for "whatsapp", and put the word in the loop's list. Count the places you typed.
Check yourself
A drawing program reads a file with one shape name per line ("circle", "square", "triangle") and must make the matching shape object for each line. Which pattern fits?
These lines use the notifier classes and the factory from this lesson. What do they print?
# the notifiers and NotifierFactory from this lesson, then:print(NotifierFactory.create("push").send("Ben", "parcel at the door"))try: print(NotifierFactory.create("post").send("Ben", "parcel at the door"))except ValueError as e: print("error:", e)// the notifiers and NotifierFactory from this lesson, then in main:System.out.println(NotifierFactory.create("push").send("Ben", "parcel at the door"));try { System.out.println(NotifierFactory.create("post").send("Ben", "parcel at the door"));} catch (IllegalArgumentException e) { System.out.println("error: " + e.getMessage());}The shop adds WhatsApp messages. What has to change?
A teammate suggests that create should return an EmailNotifier for any name it does not know, instead of reporting an error. Why does this lesson's factory report the error?
Honesty notes
- Spot the problem Factory solves: a name such as "sms" must become an object, and the choice should be made in one place.
- Write a factory with a static create method that returns the right notifier and raises an error for a name it does not know.
- Say that the code that sends messages knows only the factory and the Notifier interface.
- Say what changes for a new channel: one new class and one new branch in the factory, and nothing in the code that sends.