SECTION 03 / 6

Creational design patterns

2 min read
On this page 3 headings

Design patterns are descriptions of communicating objects and classes customised to solve a general design problem in a particular context. Elements: Problem — when and in what context to apply it; Solution — elements, relationships, responsibilities and collaborations, a template for many situations; Consequences — results, trade-offs and cost-benefit. Types: Creational — used during object creation; Structural — composition of classes/objects; Behavioural — how classes/objects interact and distribute responsibility.

3.1 Factory Method: choose what to create

Factory Method
Factory Method
Open image ↗
Factory Method

Feature: deliver a package using a courier service. Delivery has deliver(courier), and Courier is a class. Adding international couriers with a courierType if/else in deliver violates OCP. Factory pattern: replace direct object construction calls (the new operator) with calls to a special factory method.

Make Delivery and Courier abstract. NationalCourier and InternationalCourier extend Courier. NationalDelivery and InternationalDelivery extend Delivery and implement createCourier(), returning NationalCourier / InternationalCourier. In main, create a delivery object d (e.g. InternationalDelivery), call d.createCourier(), and pass the result to d.deliver(). New types, e.g. a local courier, are just new classes.

Pros: SRP and OCP. Con: code may become more complicated because of many new subclasses, so decide based on context.

3.2 Builder: construct a complicated object step by step

Builder Pattern
Builder Pattern
Open image ↗
Builder Pattern

Book has mandatory ISBN, title and cost, and optional author, published and description. Many constructors for different combinations are telescoping constructors. Builder extracts object construction out of its own class into a separate builder object.

A static Builder class has the same fields, a Builder(isbn, title, cost) constructor, one method per optional field — author(), published(), description() — and build() returning the Book. Book keeps one constructor that takes the builder. Example: new Book.Builder(isbn, title, cost).author(..).published(..).description(..).build().

Pros: construct objects step by step; SRP. Con: more complicated because of the new class and methods; skip it if there are not many optional parameters. The example is adapted from Joshua Bloch’s builder (Oracle Java Magazine).

3.3 Factory Method versus Builder

Factory Method vs Builder
Factory Method vs Builder
Open image ↗
Factory Method vs Builder

Factory Method: courier creation — which object to create? Builder: Book construction — how to build the object step by step?

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑