Keyhole Design Pattern

🔑

Feb 17, 2023·

1 min read

Play this article

The keyhole design pattern can be used when we wish to expose only a fraction of an object to another component.

If an object’s capabilities are deemed too powerful to pass around nilly willy, we may want to constrain the scope of what gets passed to the bare minimum needed by the recipient.

One way to achieve this pattern is for the powerful class to implement an interface containing only the functions to be exposed. Then the recipient can specify this interface as the type of parameter it receives.

Another way, if the scope of interest is just a single function, is to pass a handle of that function.

These techniques can be used to reduce coupling between classes. Instead of a class having the potential to call any functions of another class, it gets to call only a subset. Increasing the scope of the interaction requires widening the keyhole, which is an opportunity to reflect on whether the class structure has grown too tangled.