AlgoViz

Strategy pattern

medium 55 min

Define a family of interchangeable algorithms behind one interface.

Watch lesson4:30

Where it shows up

The same pattern appears across everyday software.

  • Java Comparator

    `List.sort` and `Collections.sort` take a `Comparator`: the ordering is the strategy, the sort is the context.

  • Python sort keys

    `sorted(rows, key=...)` takes a key function. The Sorting Techniques guide builds its examples on it.

  • Java ThreadPoolExecutor

    What to do when the queue is full is a `RejectedExecutionHandler`: abort, run in the caller, discard, or discard the oldest.

  • Passport.js

    Authentication methods are packages called strategies. The documentation uses the word for the same idea.

  • Redis

    `maxmemory-policy` selects the eviction algorithm, such as `allkeys-lru` or `allkeys-lfu`.

  • nginx

    Round robin is the default for an upstream group. `least_conn` or `ip_hash` selects another balancing method.

  • Apache Kafka producer

    `compression.type` selects none, gzip, snappy, lz4 or zstd.

  • Spring Security

    `DelegatingPasswordEncoder` picks the encoder by a prefix stored with each hash, such as `{bcrypt}`. New passwords can use a new algorithm while old ones still verify.

  • gRPC

    Load balancing is done by policies chosen by configuration, and you can register your own.

  • Active Merchant

    A Ruby library with one unified API in front of many payment gateways.