Skip to the guide

Strategy

BeginnerPattern7 pages

Strategy takes a rule that varies, gives each version of it a class of its own behind one interface, and lets the class that uses the rule hold one version at a time. The pattern was named in Design Patterns by Gamma, Helm, Johnson and Vlissides (1994), which gives its intent as "define a family of algorithms, encapsulate each one, and make them interchangeable." Interviewers listen for when you reach for it, and just as much for when you leave it out.

A camera's mode dial

Think of a camera with a mode dial on top. Pressing the button always does the same thing: the camera exposes the picture and saves it. The mode on the dial decides how it sets the exposure, whether that is auto, portrait or night. You turn the dial when the light changes, and night mode keeps its own setting for how long the shutter stays open. A fireworks mode added in an update leaves the button and the rest of the camera as they were.

In code, the camera is this page's Phone, and pressing the button is a call arriving, receive(call). The phone rings or keeps the call as missed, which is the photo it saves. The mode on the dial is the one CallRule the phone holds. Each mode is a rule class, such as AllowList, whose list of names is its own setting. Turning the dial is the owner picking a mode from ModeMenu, and the fireworks mode is a new rule class that leaves Phone unchanged.