Factory method
medium 60 minA fixed workflow with one open step that creates an object.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
One workflow, one open line, and who fills it.
Operations
Two branches
The same recipe runs in two branches. Only the mould differs.
Step 1 of 6
An order
Lee asks the hill branch for a candle. make is inherited.
Step 1: An order
class Workshop(ABC): def make(self): candle = self.take_mould() return finish(candle) @abstractmethod def take_mould(self): ...class HillBranch(Workshop): def take_mould(self): return Pillar()class HarbourBranch(Workshop): def take_mould(self): return Floating()- Watch
- The call to itself
- Result
- Two kinds, one recipe
The base class calls a method that it does not have.
In the real world
The same factory method doing real jobs. Pick one and step through it.
A factory opens a connection, then the login fails. Who closes it?
Step 1 of 4
Open
The factory opens a connection.
Step 1: Open
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A default nobody ordered
criticalA typing mistake produces the wrong product without an error.
Wrongif kind == "sms": return Sms()return Email()Rightif kind == "sms": return Sms()raise UnknownKind(kind)Casting the product back
majorThe caller depends on the class again, and breaks with the next one.
Wrongvehicle = factory.create_vehicle()if isinstance(vehicle, BmwM5): ...Rightvehicle = factory.create_vehicle()vehicle.drive()Calling it in the base constructor
criticalThe override runs before its own fields exist.
Wrongdef __init__(self): self.button = self.create_button()Rightdef button(self): if self._button is None: self._button = self.create_button() return self._buttonA subclass for a number
majorFifteen classes that differ in two integers.
Wrongclass Candle40(Workshop): def take_mould(self): return Pillar(40)RightWorkshop(make=lambda: Pillar(40))Leaking on failure
criticalThe caller never got a reference, so it can not close it.
Wrongc = Connection(name)c.login(secret)return cRightc = Connection(name)try: c.login(secret)except BaseException: c.close(); raisereturn cClass names from outside
criticalText from a request chooses which code runs.
Wrongreturn globals()[request.kind]()Rightreturn registry.create(request.kind)
Interview tips
Look for the workflow
- Same steps, one gap.
- Then it is this pattern.
- No workflow: a function.
Return the interface
- Callers know Vehicle.
- No casts.
- New or shared: say it.
Count the classes
- Parallel trees hurt.
- Pass a function instead.
- Data is a parameter.
Somebody chooses
- Choose in main.
- Unknown is an error.
- Seal the registry.