Ch.2: Design Patterns: Factory Method vs Abstract Factory
Outline
- 0:00 When a factory earns its cost
- 1:01 Direct construction
- 1:53 A factory function shares selection
- 2:40 Object return versus text return
- 3:15 Factory Method in an inherited workflow
- 4:11 Trace the overridden creation method
- 5:01 Pass the class as a simpler alternative
- 6:02 When readers and writers disagree
- 6:48 Abstract Factory supplies a matching family
- 7:43 Trace the family-based client
- 8:18 Application setup still chooses the family
- 8:57 Add a family versus add a product role
- 9:47 What the factory cannot guarantee
- 10:44 Choose by the requirement
Transcript
0:00 Factory design patterns organize object creation. You trace an export call into another function just to find which class it chooses. When is that extra tracing cost worth paying? It needs to earn its place. We'll use one document tool to compare shared selection, a replaceable creation step in an existing job, and a matching pair. Take a fictional document titled Roadmap, with status draft. Its first export is CSV: rows of text under column names. The second is JSON, structured text with named fields.
0:31 Same document, different text. The two outputs on screen are what our example actually produces. To produce either one, we need a writer object. That's an instance of a class, with a write operation that converts these records into text. A factory's product is the object it creates. And the creation decision comes before that operation runs. A factory can supply the writer without itself doing the writing. Right. Keep those two results separate: first an object, later some text. Read the direct version from top to bottom.
1:03 It checks the records, creates a CSV writer, then asks that object to write the checked records. The parentheses after the class name create the object. The dotted write call uses it. What are those short labels after the function's inputs? They're type hints. Rows means our document records; str means text. They describe the expected values, rather than performing the title check. That check belongs to our application. Here, it rejects a blank title before a writer gets created. Then the valid Roadmap record becomes the displayed CSV.
1:37 I think I'd keep this version if CSV were the only requirement. The creation choice is local, and following the function takes very little effort. Same here. A direct class call isn't a defect waiting for a pattern. We need a reason to move that choice. Now suppose the tool accepts a format name. One route chooses CSV, the other JSON. We could keep those branches in the export function. Or move them into make writer. Each branch creates and returns the appropriate writer object. An unsupported name raises an error instead of quietly choosing CSV.
2:11 A code reviewer could ask, 'The conditional is still sitting there. Have we improved anything beyond giving it a new address?' Only if sharing that selection is useful. Several callers can ask the same function for a writer. They trade duplicated selection for another call to follow. That gives the extra call a purpose: callers share selection. Refactoring Guru calls this selection function a simple factory. Source links are in the description; the writer implementations haven't changed. Let's trace the JSON caller together.
2:41 Validation runs first, then the highlighted line asks make writer for the chosen object. Walk me through those returns. Where do we get the object, and which call gives us the text? The factory branch returns a JSON writer object, which goes into writer. The next line calls that object's write operation with validated input. That call returns the JSON shown below. So the caller stores an object before asking it for text. Those two arrows have different destinations. Exactly. The factory rejects an unknown name.
3:11 Without a writer, this caller never reaches the write operation. Now contrast that function with an existing export job supplying the workflow: validate, obtain a writer, write. It offers one operation that a more specific job can replace. That's inheritance here: a new class can reuse the existing class's behavior. Replacing an inherited operation with its own version is called overriding. The base job's create writer method returns a CSV writer. Its run method calls that creation method through self, meaning this particular job instance.
3:43 So run doesn't spell out the CSV class at the creation step. It asks the job instance for a writer. What does that buy the JSON job? A narrow place to customize creation while reusing run. That overridable creation operation is Factory Method; run remains the surrounding workflow. And validation stays in run, outside that hook. A different writer doesn't get to skip the application's title check just because creation became customizable. Next, customize that creation hook: the JSON job inherits from the export job.
4:16 The name in parentheses shows that relationship. It defines its own create writer method, returning a JSON writer. I'm not sure which method that arrow reaches. Does the inherited run call the base creation method first, then replace its CSV object? No. This instance is a JSON job, so its overridden creation method is selected when run makes that call. That base implementation isn't an intermediate stop. Oh, I see. The run function is inherited unchanged; the instance determines which creation operation it reaches.
4:48 Then the writer's write operation produces JSON text. Our check confirms it's the same inherited run function. The altered step is obtaining the writer, rather than a separately copied JSON workflow. But instead of overriding that hook, a plain Python function can take a smaller route. Pass the writer class as an input, then create its object inside the export function. The call card passes the JSON writer name without parentheses. So at that point we're handing over the class, rather than creating its object?
5:19 Yes. Inside the function, the highlighted parentheses call that supplied class. The new object writes our checked record and returns the same JSON text. For this function, I'd pass the class. When would you keep the separate JSON job subclass? Suppose a library supplies run and asks applications to override create writer. The library provides the workflow; our subclass provides that creation operation. Then we can keep that inherited workflow and change its creation step. The extra class needs a job beyond making the diagram look official.
5:51 Right. A factory function centralizes a choice; Factory Method customizes creation inside inherited behavior. Passing a class can meet our simpler function's need without that inheritance. Now add a different requirement: read the exported document back. A reader turns format text into records, reversing the writer's conversion for our supported examples. For example, a CSV writer and JSON reader each have the expected operation names. But connect them, and our two-line CSV lands at a reader expecting JSON.
6:23 That mismatch raises the JSON decoding error shown here. Okay, both objects have the expected operations, but their formats disagree. Could we avoid making those two selections independently? We can ask one family factory for both: a reader and a writer that use the same format. This new requirement is about objects working together. Let's follow that family choice. The reader has to understand what its writer produces. So choosing this CSV column means taking both objects from it? The CSV reader pairs with that writer in the CSV family.
6:56 The JSON column supplies its own matching pair. Across a row, we keep the same role, meaning the object's job: reader or writer. The original Design Patterns book calls this matching-family arrangement Abstract Factory. And its interface means the creation operations this client expects. Our family classes supply those operations, so the client asks one factory for both roles. That create writer method looks familiar. Is this the same override idea as the JSON job? Yes. Each highlighted override replaces one creation operation.
7:28 That operation is a factory method. Abstract Factory names the larger arrangement: this family supplies both matching roles. Oh, so one name describes a creation operation, and the other describes the related pair. They're two descriptions of this same family. With those family operations available, read the client first. It validates the records, asks the supplied factory for a writer and a reader, then runs the write and read operations. Those first arrows create the objects. Can you walk the record through the second set, with a JSON family supplied?
8:00 The factory has supplied both JSON objects. First, the writer converts our Roadmap record into the displayed JSON text. Then that text becomes the reader's input. It recovers the record with the title Roadmap and status draft, which is what the client returns. Then who picks the family that this client gets? Before that client runs, application setup chooses its family. The format name selects a CSV family or JSON family. Any other name is rejected there. So the client lost a format branch, but the application didn't lose the decision.
8:32 We moved it to where the client gets its factory. Only that family argument changes between these checked runs. Both recover our record. Other documents need their own tests. What if the application only ever needs one stable CSV pair? I'd construct that CSV pair directly. Matching alternatives need to earn the extra structure. How does adding another format compare with adding another tool to each family? Now compare two changes to the family-based client. Imagine another format: we'd implement its reader and writer, provide their creation operations and update selection.
9:06 The client can keep its expected roles. Now suppose our client requests a preview tool from the factory, turning exported text into the Roadmap card. Could just the JSON family supply it? Then the CSV route couldn't supply that preview. If the feature must work with either format, both families need the new creation operation. These are proposed changes; our example has no preview. Ah, the new row reaches both columns. Another format fills the roles we already have; a new role reaches across the families.
9:37 Clients not using previews keep their current calls. I'd ask how likely another role is before putting all these creation operations behind one interface. But that factory interface also has a limit. Now deliberately break a family implementation. Keep its inherited CSV writer, but override its reader creation method to return a JSON reader. The client still receives something with both creation operations. Does the factory interface catch that incompatible pair by itself? No. Our test reaches the same error when CSV text enters the JSON reader.
10:10 The interface describes the requested operations; it doesn't prove the returned objects are compatible. Huh, choosing one factory closes off independent selection in the client, but a mistaken factory can still hand it the wrong combination. Check that the selected pair recovers the starting record. Separately, a blank title still fails validation. That's the application's validation rule, which runs before either object is created. Right. Correct creation wiring, correct product implementations and valid input are separate responsibilities.
10:41 A factory name doesn't certify any of them. Finally, use those limits in the four-choice guide. First, keep direct construction for a stable local choice. Second, consider a factory function when several callers need shared creation selection. Third, use Factory Method when an inherited workflow needs an overridable creation step. Fourth, consider Abstract Factory when related product roles need to change together as a family. Those last two can combine. One describes a customizable creation operation; the other organizes related products. Neither requires turning every function into a hierarchy.
11:16 And our exporter doesn't have to climb through all four choices. We changed the requirements to see what each arrangement offers and what extra tracing it costs. Before choosing a name, I'd trace what gets created and what comes back. Then check which objects the surrounding code needs to keep working together. Thanks for listening to Learning Podcasts.