Home / Design patterns

Design pattern explorer

Choose the change your system needs to absorb. Run an example and inspect the code that produces its result.

Behavioural pattern

Strategy

A print shop quotes poster batches. Its retail and partner counters use the same checkout. Give each counter a pricing function so checkout can calculate a quote with either policy.

Checkout applies one of two pricing functions.

Run the example

Implementation

Where the choice breaks down

Both functions return a total in integer cents. A subscription policy that needs a billing period would change the contract for every caller. Model the extra input before adding that policy.

Read the Strategy reference
Structural pattern

Adapter

A weather display reads degrees Celsius. Its replacement sensor returns integer tenths of a degree Fahrenheit. Translate at the sensor boundary so the display keeps its existing unit contract.

Sensor readings pass through the Celsius adapter to the display.

Run the example

Implementation

What the unit test should catch

Freezing water gives a useful fixed point. A sensor reading of 320 must yield 0 °C. Include negative readings as well. If the device gains a reserved error value, handle it at this boundary before conversion.

Read the Adapter reference
Behavioural pattern

Observer

A local build completes. Its status bar and activity log can subscribe independently. Change the subscriptions, then dispatch a build event to see which listeners receive it.

The build target sends events to subscribed views.

Run the example

Subscribers
Waiting for a build event.

Implementation

Who owns the subscription?

This demonstration uses one event target per dispatch. A production view using a long-lived event target needs a teardown path. Remove its listener when the view closes so a later event cannot update a stale view.

Read the EventTarget reference