SE322 · Chapter 6 · Lecture 2 · Annotated SlidesThe Factory Method Pattern
PDF
Overview

The Factory Method Pattern

Factory Method is a class-creational pattern: an abstract creator declares one factory method that returns a product interface, and each concrete creator subclass overrides it to decide which concrete product to instantiate. The creator’s other methods use the product only through its interface. The lecture works through a computer store (StandardComputerStore makes StandardComputer, AdvancedComputerStore makes AdvancedComputer) in C++ and Java, lists the design steps and benefits, contrasts it with Abstract Factory, and practises it on document readers and notification senders.

Intent

Define an interface for creating an object, but let subclasses decide which class to instantiate; defer instantiation to subclasses.

Four roles

Creator (abstract, declares the factory method), ConcreteCreator (overrides it), Product (interface), ConcreteProduct.

One product vs. a family

Factory Method creates one product through one overridable method; Abstract Factory creates a family through a factory object with several methods.

Benefits

Code is separated from product-specific classes, so new products need only a new creator subclass (OCP); easier reuse, maintenance and testing.

How the lecture is organized

Exam focus

Not yet on a past paper, but it fits the Final’s “which pattern? draw the class diagram” format (Final 252 Q6 did this for Builder and Singleton). Know the four roles, the code shape (abstract createX() overridden in subclasses) and the difference from Abstract Factory.

How to read this page

Every original slide is shown unchanged. Yellow marks on a slide point to a numbered note: hover or tap a mark to jump to its note, and hover a note to see its marks. Questions tagged Past exam appeared on a real paper; Prediction questions are likely angles, not confirmed.

All 24 slides
  1. 1 Slide 1
  2. 2 Lecture Outlines
  3. 3 Factory Method Design Pattern
  4. 4 Factory Method Example
  5. 5 Extra: Question – the computer store
  6. 6 Factory Method Example: class diagram
  7. 7 Extra: Steps of Factory Method
  8. 8 Factory Method Example
  9. 9 Factory Method Example
  10. 10 Factory Method Example
  11. 11 Factory Method Example: creator and product classes
  12. 12 Steps for designing with the Factory Method
  13. 13 Extra: The computer store in Java
  14. 14 Benefits of the Factory Method Pattern
  15. 15 Summary
  16. 16 Extra: Question – Document Reader
  17. 17 Extra: Document Reader class diagram
  18. 18 Document Reader class diagram
  19. 19 Extra: General order for writing classes
  20. 20 Extra: Document Reader code
  21. 21 Extra: Factory Method vs. Abstract Factory
  22. 22 Extra: Question – Notification Sender
  23. 23 Notification Sender class diagram
  24. 24 Extra: Notification Sender code
Slide 1 / 24

Slide 1

Slide 1: Slide 1

Notes

  1. Second creational-patterns lecture: Factory Method, the single-product cousin of Abstract Factory.

Slide 2 / 24

Lecture Outlines

Slide 2: Lecture Outlines

Notes

  1. The pattern and the computer-store example.

  2. The design steps.

  3. The benefits.

Slide 3 / 24

Factory Method Design Pattern

Slide 3: Factory Method Design Pattern

Notes

  1. Factory Method is a class creational pattern (it works through inheritance, so its relationships are fixed at design time) that encapsulates object creation and defers instantiation to derived classes.

  2. Intent: define an interface for creating an object, but let subclasses decide which class to instantiate.

  3. It creates one product at a time through one method. Key idea: “defer instantiation to subclasses”.

  4. Structure: (1) Creator, an abstract class or interface that declares the factory method; (2) ConcreteCreator, which overrides it; (3) Product, the interface every product implements; (4) ConcreteProduct.

Exam angle

PredictionQ1

Which pattern lets subclasses decide which concrete class to instantiate through one overridable creation method?

  1. Factory Method
  2. Abstract Factory
  3. Singleton
  4. Builder
Show answer

A. Factory Method

PredictionQ2

State the intent of the Factory Method and name its four participants.

Show answer

Define an interface for creating an object, but let subclasses decide which class to instantiate (defer instantiation to subclasses). Participants: Creator (declares the factory method), ConcreteCreator (overrides it), Product (interface), ConcreteProduct.

Slide 4 / 24

Factory Method Example

Slide 4: Factory Method Example

Notes

  1. Like Abstract Factory it has creator and product classes, but the creator needs only one creational method, for products that share the same interface.

  2. So for each product in the system there is one concrete product and one concrete creator class.

  3. Rule of thumb: Factory Method for one product type with several implementations; Abstract Factory for several product types, each with several implementations.

  4. Reading the generic diagram:

    Creator
    createProduct() in italics: abstract, the factory method. someOperator() is a normal method that calls createProduct() and uses the result.
    ConcreteCreator
    Inherits from Creator (solid line, hollow triangle) and implements createProduct().
    «interface» Product / ConcreteProduct
    ConcreteProduct realises Product (dashed line). The arrow from ConcreteCreator to ConcreteProduct shows which product it creates.
Slide 5 / 24

Extra: Question – the computer store

Slide 5: Extra: Question – the computer store

Notes

  1. The scenario: an electronics store sells standard (affordable) and advanced (gaming) computers.

  2. Each store type builds only its own kind: the Standard Store builds standard computers, the Advanced Store advanced ones.

  3. Customers get a common interface: ask a store for a computer and display its details (monitor, CPU, keyboard, cost).

  4. New categories (Workstation Store, Budget Store) must be addable without changing existing code.

  5. Tasks: identify the pattern (Factory Method: one product type, a creator subclass per variant), write the code, draw the class diagram.

Slide 6 / 24

Factory Method Example: class diagram

Slide 6: Factory Method Example: class diagram

Notes

  1. ComputerStore (abstract creator): declares the abstract factory method createComputer(type), returning a Computer, and displayComputer(type), which displays the computer that createComputer produces.

  2. StandardComputerStore and AdvancedComputerStore (concrete creators) each implement createComputer() to return their own kind of Computer.

  3. Computer (product interface): displayMonitorInfo(), displayCpuInfo(), displayKeyboardInfo(), displayCost(). Note the italics in the diagram: abstract operations.

  4. StandardComputer and AdvancedComputer (concrete products) implement those display methods.

  5. Summary: different Computers are created without changing client code; the creation logic lives in ComputerStore and its subclasses.

Slide 7 / 24

Extra: Steps of Factory Method

Slide 7: Extra: Steps of Factory Method

Notes

  1. The writing order: (1) the Computer interface; (2) the concrete computers StandardComputer, AdvancedComputer; (3) the abstract ComputerStore with createComputer() and displayComputer(); (4) the concrete stores; (5) main to test. Products first, then creators, then the client: the same order you should use in an exam answer.

Slide 8 / 24

Factory Method Example

Slide 8: Factory Method Example

Notes

  1. The C++ creator class:

    CodeWhat it does
    class Computer;Forward declaration: ComputerStore only needs to know the type exists.
    class ComputerStore {The creator. It is abstract, so specific derived stores are needed.
    virtual Computer* createComputer(std::string type);The factory method: virtual lets derived classes override it (made pure virtual with = 0 in a strictly abstract creator).
    void displayComputer(std::string type); };A normal method that will use the created computer.
  2. How to spot abstract methods: in code, look for the virtual keyword (C++) or abstract (Java); in UML diagrams, methods in italics.

Slide 9 / 24

Factory Method Example

Slide 9: Factory Method Example

Notes

  1. displayComputer in C++:

    CodeWhat it does
    void ComputerStore::displayComputer(string type) {Defined once, in the abstract creator.
    Computer* computer = createComputer(type);Delegates creation to the derived class through the factory method: this line is the whole pattern.
    computer->displayMonitorInfo(); computer->displayCpuInfo();Uses the product only through the Computer interface.
    computer->displayKeyboardInfo(); computer->displayCost(); }The output differs by store, but this code never changes.
Slide 10 / 24

Factory Method Example

Slide 10: Factory Method Example

Notes

  1. A concrete creator in C++:

    CodeWhat it does
    Computer* StandardComputerStore::createComputer(string type) {The standard store’s override of the factory method.
    if (type.compare("standard") == 0) computer = new StandardComputer;It can only build standard computers.
    else computer = new NullComputer;Anything else returns a NullComputer: an object that does nothing, so callers never get a null pointer.
    return computer; }Clients are responsible for freeing the returned object (C++).
Slide 11 / 24

Factory Method Example: creator and product classes

Slide 11: Factory Method Example: creator and product classes

Notes

  1. The complete example diagram. Creator classes: abstract ComputerStore (createComputer(type): Computer, displayComputer(type)) with subclasses StandardComputerStore and AdvancedComputerStore.

  2. Product classes: «interface» Computer, realised by StandardComputer and AdvancedComputer; the arrows from each store to its computer show which product each creator makes. Products must obey the product interface.

Slide 12 / 24

Steps for designing with the Factory Method

Slide 12: Steps for designing with the Factory Method

Notes

  1. Step 1: identify and design the product interface (Computer).

  2. Step 2: design the concrete products that realise it (StandardComputer, AdvancedComputer).

  3. Step 3: design the factory (creator) interface, ComputerStore, with one abstract factory method that delegates creation to derived classes.

  4. Step 4: design one concrete factory (creator) per product from step 2.

  5. Step 5: associate each factory with its product.

Exam angle

PredictionQ1

Apply the Factory Method to a logistics app where RoadLogistics creates Trucks and SeaLogistics creates Ships. Name the classes and the factory method.

Show answer

Product interface: Transport (deliver()). Concrete products: Truck, Ship. Abstract creator: Logistics with abstract createTransport(): Transport and planDelivery() that calls createTransport().deliver(). Concrete creators: RoadLogistics returns new Truck(); SeaLogistics returns new Ship().

Slide 13 / 24

Extra: The computer store in Java

Slide 13: Extra: The computer store in Java

Notes

  1. The same example in Java:

    CodeWhat it does
    abstract class ComputerStore { public abstract Computer createComputer(String type);The factory method, implemented by subclasses.
    public String displayComputer(String type) { Computer c = createComputer(type); … }A helper that formats the product info, using only Computer.
    class StandardComputerStore extends ComputerStore { @Override public Computer createComputer(String type) {The standard creator…
    if ("standard".equalsIgnoreCase(type)) return new StandardComputer();…builds a StandardComputer…
    return new NullComputer("Standard store only builds 'standard' computers"); } }…or a NullComputer with a message.
    class AdvancedComputerStore extends ComputerStore { … new AdvancedComputer() … }The advanced creator, same shape.
  2. Products and client:

    CodeWhat it does
    interface Computer { String displayMonitorInfo(); String displayCpuInfo(); String displayKeyboardInfo(); String displayCost(); }The product interface.
    class StandardComputer implements Computer { … "Monitor: 24\" 1080p" … "Cost: $699" }Concrete products return their own details.
    ComputerStore standardStore = new StandardComputerStore(); standardStore.displayComputer("standard");The client works through ComputerStore.
    advancedStore.displayComputer("standard");The mismatch example: the advanced store asked for a standard computer returns the NullComputer message.
Slide 14 / 24

Benefits of the Factory Method Pattern

Slide 14: Benefits of the Factory Method Pattern

Notes

  1. It separates code from product-specific classes, so the same code works with existing and newly created products. New product = new creator subclass, no edits elsewhere (OCP).

  2. Development is more efficient: different developers can work on different creators and products at the same time.

  3. Specific parts are easier to reuse and maintain.

  4. Testability improves: a test can subclass the creator to return a fake product.

Exam angle

PredictionQ1

True or false: the Factory Method helps follow the Open-Closed Principle when new product types are added.

Show answer

True — A new product needs a new concrete product and a new creator subclass; existing creators and client code are not modified.

Slide 15 / 24

Summary

Slide 15: Summary

Notes

  1. This lecture: Factory Method.

  2. Next: Builder and Singleton, which complete the creational patterns (both were on Final 252).

Slide 16 / 24

Extra: Question – Document Reader

Slide 16: Extra: Question – Document Reader

Notes

  1. Scenario: a document-reader framework handles PDF, Word and Excel files. An abstract DocumentReader base class implements the overall reading workflow.

  2. It declares a single overridable method whose job is to return the parser to use: that is the factory method.

  3. One common Parser interface is used by all concrete parsers (the product).

  4. Each concrete reader (PdfReader, WordReader, ExcelReader) overrides that method to return the right parser; a new type (PowerPoint, Text) means a new reader subclass, with no client changes.

  5. Answer: Factory Method. The next slides give the UML and code.

Exam angle

PredictionQ1

A DocumentReader framework must create the right Parser for PDF, Word or Excel files through one overridable method. Which pattern, and what are the classes?

Show answer

Factory Method. Parser is the product interface (parse()); PdfParser, WordParser, ExcelParser implement it. DocumentReader is the abstract creator with abstract createParser(): Parser and a read() workflow that calls createParser().parse(). PdfReader, WordReader and ExcelReader extend DocumentReader and return their parser.

Slide 17 / 24

Extra: Document Reader class diagram

Slide 17: Extra: Document Reader class diagram

Notes

  1. The solution diagram: «abstract» DocumentReader with createParser(t): Parser; PdfReader, ExcelReader and WordReader extend it (creator classes).

  2. «Interface» Parser with Parse(), realised by PdfParser, ExcelParser and WordParser (product classes). Each reader points to the parser it creates.

Slide 18 / 24

Document Reader class diagram

Slide 18: Document Reader class diagram

Notes

  1. The same diagram labelled with the pattern’s roles: creator classes on the left (DocumentReader and its readers), product classes on the right (Parser and its parsers). Products must obey the Parser interface; each concrete reader is paired with exactly one concrete parser.

Slide 19 / 24

Extra: General order for writing classes

Slide 19: Extra: General order for writing classes

Notes

  1. 1. Product: the common behaviour (Parser with parse()).

  2. 2. Concrete products: one per variant (PdfParser, WordParser, ExcelParser).

  3. 3. Creator: the abstract class that declares the factory method (DocumentReader with createParser()).

  4. 4. Concrete creators: implement the factory method to return the right product (PdfReader → PdfParser…).

  5. 5. Client: main uses the creator type, never the concrete products directly.

Slide 20 / 24

Extra: Document Reader code

Slide 20: Extra: Document Reader code

Notes

  1. The Java solution:

    CodeWhat it does
    abstract class DocumentReader { public abstract Parser createParser(); // Factory Method }1) The creator.
    class PdfReader extends DocumentReader { public Parser createParser() { return new PdfParser(); } }2) Concrete creators, one per format (WordReader, ExcelReader are the same).
    interface Parser { void parse(); }3) The product.
    class PdfParser implements Parser { public void parse() { System.out.println("Parsing PDF..."); } }4) Concrete products.
    DocumentReader reader; reader = new PdfReader(); reader.createParser().parse();5) The client holds a DocumentReader; switching to new WordReader() changes the output to “Parsing Word...” without other changes.
Slide 21 / 24

Extra: Factory Method vs. Abstract Factory

Slide 21: Extra: Factory Method vs. Abstract Factory

Notes

  1. Purpose: Factory Method defines a single factory method to create one product at a time; Abstract Factory provides an interface for creating families of related products.

  2. Factory and products: one (often parameterised) method whose subclasses decide the product, with one product hierarchy (Parser → PdfParser, WordParser); versus a factory interface with one method per product type and several related hierarchies (Button, Checkbox for Windows and Mac).

  3. Flexibility and client: Factory Method is lighter, used when only one kind of product is needed, and the client calls a single method (createParser()); Abstract Factory is more complex but guarantees consistency across a family, and the client calls several methods (createButton(), createCheckbox()). Examples: DocumentReader creates one parser; GUIFactory creates a set of widgets.

Exam angle

PredictionQ1

Give two differences between the Factory Method and the Abstract Factory patterns.

Show answer

Factory Method creates one product through one overridable method in a creator subclass (inheritance, class scope); Abstract Factory creates a family of related products through a factory object with one method per product type (composition, object scope). Factory Method has one product hierarchy; Abstract Factory has several related hierarchies and guarantees the family is consistent.

Slide 22 / 24

Extra: Question – Notification Sender

Slide 22: Extra: Question – Notification Sender

Notes

  1. A second exercise: a notification-sender framework sends messages through Email, SMS or Push. The abstract base class NotificationSender implements the workflow (validate message → create channel → send).

  2. It declares one overridable method that returns the Channel to use; one common Channel interface; each sender subclass (EmailSender, SmsSender, PushSender) overrides that method; a new channel (WhatsApp) means a new sender and channel class, no client changes.

  3. Questions: which pattern (Factory Method), draw the UML, write simple Java. Solutions on slides 23–24.

Slide 23 / 24

Notification Sender class diagram

Slide 23: Notification Sender class diagram

Notes

  1. Creator classes: «abstract» NotificationSender with createChannel(): Channel; EmailSender, SMSSender and PushSender extend it.

  2. Product classes: «Interface» Channel with send(String), realised by EmailChannel, SmsChannel and PushChannel. Each sender creates its matching channel.

Slide 24 / 24

Extra: Notification Sender code

Slide 24: Extra: Notification Sender code

Notes

  1. The Java solution:

    CodeWhat it does
    interface Channel { void send(String msg); }The product.
    class EmailChannel implements Channel { public void send(String msg) { System.out.println("Email: " + msg); } }Concrete products (SmsChannel, PushChannel similar).
    abstract class NotificationSender { public void notify(String msg) { Channel channel = createChannel(); channel.send(msg); }The workflow, written once in the creator…
    protected abstract Channel createChannel(); }…and the factory method it relies on.
    class EmailSender extends NotificationSender { protected Channel createChannel() { return new EmailChannel(); } }Concrete creators decide the channel (SmsSender, PushSender similar).
  2. notify() is the “some operation” of the generic structure: it never names a concrete channel, which is exactly what makes adding WhatsApp a matter of two new classes.