To learn about policies, we are going to model a car. Modern cars have many interchangeable components such as engines, transmissions, and safety devices. Some cars have 4 cylinder engines, manual transmissions, and seat belts, while others have rotary engines, continuously variable transmissions, and roll cages. We want our model to be flexible and support any combination of these dimensions. Here’s one way to do it:

Here, Car has three members: engine, transmission, and safetyDevice, which conform to respective policy protocols. Let’s implement the policy protocols and classes that allow Car instances to be so flexible:

Here we started with engines. First, we defined our policy protocol, EnginePolicy. This provides some structure to our policy classes. Then we made each policy class conform to the EnginePolicy protocol by defining the applyGas method and a computed description property.

Let’s define policies for transmissions and safety devices as well:

Now we can instantiate cars with any combination of these policies. Here are some valid instances:

One great benefit of designing using policies like this is being able to combine policies with one another to produce varied instances. There are 3 types of engines, transmissions, and safety devices that a car can have in this model. Each policy has 3 implementations. That means that 3³ = 27 unique cars can be created!

This simple but powerful design pattern allows for exponential combinations of behavior.