This pattern allows an object to change its behavior at runtime by choosing from a set of predefined behaviors. This can be useful when you want to change the behavior of an object based on the needs of the client, and when you want to abstract the details of the behavior from the object itself.
Here is an example of the strategy pattern in JavaScript:
}
}
}
}
strategy.
// Output: 'Behavior 1'
strategy.
strategy.
// Output: 'Behavior 2'
In this example, the Strategy class is a class that represents an object that can change its behavior at runtime by choosing from a set of predefined behaviors. The Strategy class has a behavior property that stores the current behavior, a setBehavior() method for changing the behavior, and a performBehavior() method for executing the current behavior.
To use the strategy pattern, we create an instance of the Strategy class, and then use the setBehavior() method to change the behavior of the object. We can then call the performBehavior() method to execute the current behavior. This allows the object to change its behavior at runtime based on the needs of the client, without the client having to know the details of the behavior.