Design Pattern: Strategy Pattern

Tram Ho

I. Introduction:


Strategy Pattern is a Behavior Design Pattern . It allows us to define business logic into different objects that can be substituted for each other at runtime. Strategy Pattern consists of the main components:

  • Object using Strategy : is the object using the Concrete Strategy . Inside the object will contain a property whose data type is Strategy Protocol .
  • Strategy Protocol : Defines the properties and methods that all Concrete Strategy must have and implement them.
  • Concrete Strategy : classes will implement details of properties and methods declared in Strategy Protocol . It will contain the business logic specific to each class.

II. How it works:


Strategy Pattern works similarly to the Delegate Pattern . The concrete actions of a class will not be performed directly but will delegate that to Concrete Strategy . The same job but will be able to handle it differently depending on which Concrete Strategy we are using.

III. When was the Strategy Pattern used?


Strategy Pattern is used when there are two or more interchangeable behaviors during the project runtime.

IV. For example:


Declare Strategy Protocol.

Create Concrete Strategy.

The context will be the object of Strategy.

Use:

V. References:


Share the news now

Source : Viblo