Design Patterns in Apex: Strategy Pattern


TOM CARMAN

1. What does it do?

The strategy pattern allows an algorithm’s behaviour to be chosen at runtime. It can be used to define a family of algorithms that solve a common goal. It permits unique logic per algorithm via encapsulation, but ensures that all algorithms are interchangeable at runtime. The abstraction is captured by an interface, whilst individual implementations are buried in derived classes.

2. When should it be used?

The strategy pattern should be used when you wish to perform an operation that has a common end-goal, but has several different approaches to get there – which can be chosen by the client at runtime.

Some real-world Salesforce based examples:

  • You wish to retrieve the local weather for an Account based on its location, but need to use several different Weather APIs to get the best results – based on the country which the Account is located in.
  • You…

View original post 582 more words