Skip to content
Ameen Abozaid
In reviewJNR-005-L04

Strategy

  • Lesson 4 of 10
  • 10 min read
  • Junior
On This Lesson 4 topics

The content for this lesson is written and waiting for review. The outline below shows what it covers. It will be published once it is approved.

In this lesson

swap an algorithm without changing the caller.

Planned topics

  • Problem: many if/else branches choose between ways of doing one thing.
  • Define an interface; each way is a class (or a lambda).
  • The caller holds the interface and does not care which one.
  • Example: shipping cost: standard, express, pickup.
  • JDK example: Comparator passed to sort.
Draft outline details

Demonstration

java
interface ShippingStrategy { Money cost(Order o); }
class Express implements ShippingStrategy { ... }
Money total = strategy.cost(order);

Check your understanding

What does Strategy replace?

Show answer

A chain of if/else or a switch choosing an algorithm.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.