Design pattern Strategy in nutshell

Luiz Gustavo De O. Costa
2 min readOct 6, 2019

--

The behavioral strategy help us to decouple if/else code.

  1. Definition

The definition in nutshell by GOF[2] is Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

2. How to use

This pattern is drawn in UML for generic and example

2.1 GOF

GOF strategy diagram
GOF strategy diagram

2.2. Example

Strategy example
Example strategy diagram

Code

PrinterStrategy
Context
Main class

Conclusion

After make some tests and modeling this small example, this pattern helps to avoid a lot of if/else decisions and make the code more clear to read, decouple de algorithm as the PrintStrategy shows.

The complete code is available on my github.

References

--

--

Luiz Gustavo De O. Costa
Luiz Gustavo De O. Costa

Written by Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices

No responses yet