Strategy pattern: Transcoder example

By | 22 June, 2014

We’re going to create a little service in order to transform from text message to the different kind of code:

  • ASCII code: represent the text as the secuence of numeric codes of the character of the messageStrategy Pattern - UML schema
  • Braille code
  • Morse code

 

But we’d like:

  • At creation time of the service: set up the code of the output
  • During the execution: change the type of the output code

In order to achieve this goal we’re going to use the “Strategy Pattern”:

The Strategy Pattern define a family of algorithms, encapsulates each one, and makes them interchangable.

Strategy lets the algorithm vary independently from clients that use it.

Components of the Strategy pattern:

  • Context: who needs to change its behavior dinamically
    • setStrategy(strategy: Strategy): method to change the behavior dinamically
  • Strategy: abstract base for every possible behavior (algorithm) to apply to the context.
    • strategicMethod():  part of the Strategy contract
  • ConcreteStrategy: each of the concrete implementations for the strategy 
    • strategyMethod(): concrete implementation of the strategy contract.

Developing the example:

Strategy Pattern - TranscoderExample

Fundamentals of the pattern

  • OO basics:
    • Abstraction.
    • Encapsulation.
    • Polymorphism.
    • Inheritance.
  • OO principles:
    • Encapsulate what varies.
    • Favor composition over inheritance.
    • Program to interface, not implementations.

References

Leave a Reply

Your email address will not be published. Required fields are marked *