STRATEGY PATTERN

Aymen Afia
Oct 17, 2020

The strategy pattern defines a family of interchangeable objects that can be set or switched at runtime. This pattern has three parts:

  • The object using a strategy. This is most often a view controller when the pattern is used in iOS app development, but it can technically be any kind of object that needs interchangeable behavior. (This is the object that you want to change its behavior).
  • The strategy protocol defines methods that every strategy must implement.
  • The strategies are objects that conform to the strategy protocol.

When should you use it?

Use the strategy pattern when you have two or more different behaviors that are interchangeable.

  • Example:

Here you can see 3 concrete types, conforms our Strategy protocol, we just need to know our service name, and fetch the song for it.

Of course this is a basic exampl, the decision should in the strategy layer not by the client (the viewcontroller), To decouple the client from a family of strategies.

Key points

  • The strategy pattern defines a family of interchangeable objects that can be set or switched at runtime.
  • The strategy pattern is similar to the delegation pattern: Both patterns use a protocol for flexibility. Unlike the delegation pattern, however, strategies are meant to be switched at runtime, whereas delegates are usually fixed.
  • the strategy pattern hides the specific algorithms from the clients
  • the strategy pattern decouple the client from a family of strategies
  • We can reuse the strategies in different clients instead of duplicating a lot of if/else

--

--