You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: BehavioralPatterns/Strategy/README.md
+34-14Lines changed: 34 additions & 14 deletions
Original file line number
Diff line number
Diff line change
@@ -4,27 +4,21 @@ The Strategy Pattern
4
4
* defines a family of algorithms,
5
5
* encapsulates each one, and
6
6
* make them interchangeable.
7
+
7
8
Strategy lets the algorithm vary independently from clients that use it.
8
9
9
-

10
+
## Problem
10
11
11
-
**Usage**
12
-
```cs
13
-
Duckmallard=newMallardDuck();
14
-
mallard.PerformQuack();
15
-
mallard.PerformFly();
12
+
- A class should be configured with an algorithm instead of implementing an algorithm directly.
13
+
- An algorithm should be selected and exchanged at run-time.
16
14
17
-
// change the flying behavior dynamically
18
-
Duckmodel=newModelDuck();
19
-
model.PerformFly(); // default behavior
20
-
model.FlyBehavior=newFlyRocketPowered(); // set a different flying behavior at runtime
21
-
model.PerformFly();
22
-
```
15
+
## Solution
23
16
17
+
- Define an interface `Strategy` for performing an algorithm and define separate classes that implement the `Strategy` interface and encapsulate an algorithm in different ways.
24
18
25
19
## Common Structure
26
20
27
-

21
+

28
22
29
23
* Strategy (SortStrategy)
30
24
* declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy
@@ -35,4 +29,30 @@ model.PerformFly();
35
29
* maintains a reference to a Strategy object
36
30
* may define an interface that lets Strategy access its data.
- A context may pass all data required by the algorithm to the strategy when an algorithm is called.
35
+
- A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context; thereafter clients interact with the context exclusively.
36
+
37
+
## Benefits
38
+
39
+
## Drawbacks
40
+
41
+
## Example
42
+
43
+

44
+
45
+
**Usage**
46
+
```cs
47
+
Duckmallard=newMallardDuck();
48
+
mallard.PerformQuack();
49
+
mallard.PerformFly();
50
+
51
+
// change the flying behavior dynamically
52
+
Duckmodel=newModelDuck();
53
+
model.PerformFly(); // default behavior
54
+
model.FlyBehavior=newFlyRocketPowered(); // set a different flying behavior at runtime
0 commit comments