TMP: Policy based design

policy

What is a policy?

  • Is a compile time variant of the strategy pattern
  • It refers to building a class out of parts

 

Where can we find an example of a policy?

STL is full of them. Take, for example, the STL containers.

The Allocators are policy template parameters for all STL containers.

 

Let’s start with an interface for a logger class.

Let’s assume that LogInfo contains info related to the log (channel, type, verbosity) and SourceInfo contains info related to location (file name, line number etc)

 

Now we have to create an implementation for it

 

What happens when we need various implementation of the same logger class?

What if…

1.We want to have another one to write to the console, or to the file?

  • Create more classes (ConsoleLogger, FileLogger)

2.We want to use functionality from two separate classes? (format type from ConsoleLogger, but output to file)

  • Add flags in the class itself? => waste of space
  • Decorator pattern? => it relies on functions calling each other so we would have more then once being called
  • Strategy pattern? => Could work, but: strategy is determined at runtime, and can be changed on the fly.

A policy, being determined at compile time, is generally only useful for special situations where you want different application logic on a per-binary basis. 

 

First, we need to split the responsibility. What does a logger do?

  • filters the incoming message based on certain criteria
  • formats the message in a certain way
  • writes the formatted message to a certain output

 

Policy Implementation

The implementation for the Log function may look like this

 

Now we need to set it all up for compilation

Will the code above compile? No, we need to define the functions that are used inside the class.

 

Filter Policies example

The same thing would be for the formatter or the writer themselves.

 

Assembly line

Now we only need to use the different policy classes

 

Class template with default policies

Not all the policies need to be provided by the user. We can set them to some default policy, as the STL containers do with the memory allocators.

 

Composed policies

We can also combine policies into a bigger policy of the same type.

 

The full implementation of the policy based design is also available on github here.

 

Leave a comment

Your email address will not be published.