Strategy
Updated: 03 September 2023
The strategy pattern is about using composition instead of inheritence
The strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. The algorithm can vary independent of clients using it
Algorithm/implementation is decoupled from its clients
This works by creating an object which wraps the behaviour we want to implement in a family of classes, allowing clients to choose which behaviour they would like to implement by referencing the interface that these behaviours implement.
Example
Definition of Classes
1namespace DesignPatterns.Strategy2{3 public class User {4 // strategy to be used for logging in a user5 // this is what we want to change depending on an implementation6 private ILoginStrategy _loginStrategy { get; set; }7
8 public string Username { get; set; }9 public string Password { get; set; }10
11 // we set the behaviour when instantiating12 public User(ILoginStrategy loginStrategy)13 {14 this._loginStrategy = loginStrategy;15 }16
17 // we can possibly change the strategy later18 public void SetLoginStrategy(ILoginStrategy loginStrategy)19 {20 this._loginStrategy = loginStrategy;21 }22
23 // login function that can be called by a consumer of this class24 public bool Login() => _loginStrategy.Execute(Username, Password);25 }26
27 // interface to define login strategies28 public interface ILoginStrategy29 {30 public bool Execute(string username, string password);31 }32
33 // login strategy for logging in from a local service34 public class LocalLoginStrategy: ILoginStrategy35 {36 public bool Execute(string username, string password) => true;37 }38
39 // login strategy for logging in from a remote service40 public class RemoteLoginStrategy : ILoginStrategy41 {42 public bool Execute(string username, string password) => false;43 }44}
Usage
1var user = new User(new LocalLoginStrategy()) {2 Username = "user",3 Password = "Password"4};5
6// calling this uses the LocalLoginStrategy7user.Login();8
9user.SetLoginStrategy(new RemoteLoginStrategy());10
11// calling this uses the RemoteLoginStrategy12user.Login();