Navigation:  Appendix B: Dolphin Pattern Book > Miscellaneous Patterns >

Policy

Previous pageReturn to chapter overviewNext page

Context

The behaviour of any object is defined by the methods in its class. You are creating a New Method that implements an algorithm which is not specific to the class and could probably be re-used in other situations. How should you go about coding this situation for maximum flexibility?

Solution

Encapsulate the implementation of the algorithm in its own class, which allows the algorithm to be pluggable and reuseable. So, don't hard code the algorithm directly in the class where it is used (the context). Instead, implement the algorithm in its own Policy class.

The end result will be that:

1.the algorithm can be reused in other contexts
2.a new algorithm can be swapped in in future causing minimal disruption
3.object behaviour can be configured on an instance basis, rather than by using subclassing (see Inheritance vs Composition).

Consequences

The Policy will require information about the context. This information is normally passed in the form of parameters to it's Instance Creation Method. The actual amount of information required by the policy object will depend on the algorithm being implemented so it may be appropriate for the context to pass itself to the instance creation method in order to give the policy full access to all of its details.

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.

An 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 routed through the network of views and presenters to find their eventual point of action (command target).

Related Patterns

Inheritance vs Composition