Java · Advanced level

Advanced level · Module 2: Modern Java Language and Design · Lesson 3 of 4

Common Design Patterns

Recognise and apply the strategy, factory, builder and observer patterns where they solve a real problem.

In this lesson you will

  • Apply the strategy and factory patterns to remove conditional logic
  • Use builder and observer appropriately

Key concepts

strategyfactorybuilderobserverpattern misuse

The lesson

Design patterns are named solutions to recurring problems. Strategy puts interchangeable algorithms behind an interface: a DiscountStrategy can be a student, staff or bulk discount, chosen at run time instead of through if/else chains.

A factory method creates objects without callers knowing the exact class, for example PaymentFactory.forCode("MOMO"). A builder constructs objects with many optional fields readably: Report.builder().title("Q1").region(JUBA).build().

Observer lets objects subscribe to events, such as sending a notification when an appointment is booked. Patterns are tools, not goals: adding one where a simple method would do makes code harder to read.

Step by step

  1. Replace an if/else discount calculation with a strategy interface.
  2. Add a factory that returns the strategy for a customer type.
  3. Create a builder for a report with optional fields.
  4. Discuss one place where a pattern would be overkill.

Practice activity

Complete the pricing refactor activity, adding a new 'seasonal discount' by writing one new class only.

Expected result: The new discount works without editing existing discount classes, and all tests pass.

Check your understanding

  1. Which pattern replaces a chain of if/else choosing an algorithm?

    Show answer

    Strategy.

  2. When is a design pattern a bad idea?

    Show answer

    When it adds complexity to a problem a simple method or class already solves.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.