Pattern: Policy


Context

The behaviour of an object is defined by the methods in its class. Some methods implement algorithms which are not specific to the class and could be used elsewhere.

Solution

Encapsulate the implementation of an algorithm in its own class. This allows reuse of algorithms and makes them interchangeable.

Don't hardcode the algorithm in the class where it is used (the context). Instead, implement the algorithm in a separate Policy class. This means that:

The Policy will require information about the context. This information is passed to the Policy in the form of parameters. The amount of information required by the Policy will depend on the algorithm implemented by the Policy. It may be appropriate for the context to pass itself to the Policy in order to give the Policy access to all the details of the context.

Example

Imagine using a Policy to handle errors in an application. Errors should be handled differently depending on the type of user running the application. For example a user should be shown a polite message, whereas a developer will be shown the error code and the stack trace.

The Abstract Class ErrorPolicy (a subclass of Object) defines the protocol, which in this case, is just the #error: method.

ErrorPolicy>>error: anError
        "Handle the error event defined by anError.
        Overridden by concrete subclasses."

        ^self subclassResponsibility

The concrete subclasses DeveloperErrorPolicy, TesterErrorPolicy and UserErrorPolicy override the #error: method in the following ways:

UserErrorPolicy>>error: anError
        "Handle the error event defined by anError.
        Show the error message in a dialog box."
        ...
TesterErrorPolicy>>error: anError
        "Handle the error event defined by anError.
        Show the error code and log it to a file."
        ...
DeveloperErrorPolicy>>error: anError
        "Handle the error event defined by anError.
        Show the error code and dump the stacktrace."
        ...

The application selects the ErrorPolicy which is appropriate for the user.

Known Uses

CommandPolicy is a Policy class which defines how menu commands should be handled.

Related Patterns