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

1
namespace DesignPatterns.Strategy
2
{
3
public class User {
4
// strategy to be used for logging in a user
5
// this is what we want to change depending on an implementation
6
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 instantiating
12
public User(ILoginStrategy loginStrategy)
13
{
14
this._loginStrategy = loginStrategy;
15
}
16
17
// we can possibly change the strategy later
18
public void SetLoginStrategy(ILoginStrategy loginStrategy)
19
{
20
this._loginStrategy = loginStrategy;
21
}
22
23
// login function that can be called by a consumer of this class
24
public bool Login() => _loginStrategy.Execute(Username, Password);
25
}
26
27
// interface to define login strategies
28
public interface ILoginStrategy
29
{
30
public bool Execute(string username, string password);
31
}
32
33
// login strategy for logging in from a local service
34
public class LocalLoginStrategy: ILoginStrategy
35
{
36
public bool Execute(string username, string password) => true;
37
}
38
39
// login strategy for logging in from a remote service
40
public class RemoteLoginStrategy : ILoginStrategy
41
{
42
public bool Execute(string username, string password) => false;
43
}
44
}

Usage

1
var user = new User(new LocalLoginStrategy()) {
2
Username = "user",
3
Password = "Password"
4
};
5
6
// calling this uses the LocalLoginStrategy
7
user.Login();
8
9
user.SetLoginStrategy(new RemoteLoginStrategy());
10
11
// calling this uses the RemoteLoginStrategy
12
user.Login();

References