Skip to content

Commit e2ea2db

Browse files
committed
feat: add Strategy pattern implementation with examples
Add comprehensive implementation of the Strategy behavioral design pattern, including: - Detailed documentation and pattern explanation - Multiple practical examples: - Basic operations (add/subtract/multiply) - Sorting algorithms (bubble/selection sort) - Storage data sources - Payment processing - UML diagrams and component breakdowns - Use cases and best practices
1 parent 382f20f commit e2ea2db

File tree

8 files changed

+706
-0
lines changed

8 files changed

+706
-0
lines changed
Lines changed: 368 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,368 @@
1+
<div id="top"></div>
2+
3+
# Strategy Behavioral Design Pattern
4+
5+
- Strategy is a
6+
- behavioral design pattern
7+
- that lets you define a family of algorithms,
8+
- put each of them into a separate class,
9+
- and make their objects interchangeable.
10+
11+
12+
13+
<details>
14+
<summary> <h2 style="display: inline;"> Sections</h2> </summary>
15+
16+
- [Strategy Behavioral Design Pattern](#strategy-behavioral-design-pattern)
17+
- [Definitions](#definitions)
18+
- [Components \&\& Diagrams (UML class || Sequence diagrams).](#components--diagrams-uml-class--sequence-diagrams)
19+
- [Components By Guru](#components-by-guru)
20+
- [1. Context:](#1-context)
21+
- [2. Strategy interface:](#2-strategy-interface)
22+
- [3. Concrete Strategies:](#3-concrete-strategies)
23+
- [4. Client:](#4-client)
24+
- [Components By geeksforgeeks](#components-by-geeksforgeeks)
25+
- [1. Context](#1-context-1)
26+
- [2. Strategy Interface](#2-strategy-interface-1)
27+
- [3. Concrete Strategies](#3-concrete-strategies-1)
28+
- [4. Client](#4-client-1)
29+
- [What problems can it solve || When to Use || Use Cases](#what-problems-can-it-solve--when-to-use--use-cases)
30+
- [The Strategy Design Pattern can be useful in various scenarios, such as:](#the-strategy-design-pattern-can-be-useful-in-various-scenarios-such-as)
31+
- [Examples](#examples)
32+
- [Operations with context Example](#operations-with-context-example)
33+
- [Sorting Example](#sorting-example)
34+
- [Storage Data Source Example](#storage-data-source-example)
35+
- [Payment Example](#payment-example)
36+
- [Summery](#summery)
37+
- [Sources](#sources)
38+
</details>
39+
40+
41+
## Definitions
42+
43+
- <details>
44+
<summary> <h3 style="display: inline;"> Tutorial Point</h3> </summary>
45+
46+
- behavioral patterns.
47+
- In Strategy pattern -> A class behavior or its algorithm can be changed at run time
48+
49+
</details>
50+
51+
- <details>
52+
<summary> <h3 style="display: inline;"> geeksforgeeks.org</h3> </summary>
53+
54+
- allows you to define a family of algorithms or behaviors,
55+
- put each of them in a separate class,
56+
- and make them interchangeable at runtime.
57+
- **This pattern is useful when you want to dynamically change the behavior of a class without modifying its code.**
58+
59+
</details>
60+
61+
62+
- <details>
63+
<summary> <h3 style="display: inline;">refactoring.guru</h3> </summary>
64+
65+
- Strategy is a
66+
- behavioral design pattern
67+
- that lets you define a family of algorithms,
68+
- put each of them into a separate class,
69+
- and make their objects interchangeable.
70+
71+
</details>
72+
73+
74+
## Components && Diagrams (UML class || Sequence diagrams).
75+
76+
### Components By Guru
77+
78+
<img style="background-color:#554777" src = "assets/structure_pattern_guru.png">
79+
80+
#### 1. Context:
81+
- maintains a reference to one of the concrete strategies and
82+
- communicates with this object only via the strategy interface.
83+
84+
#### 2. Strategy interface:
85+
- is common to all concrete strategies.
86+
- It declares a method the context uses to execute a strategy.
87+
88+
#### 3. Concrete Strategies:
89+
- implement different variations of an algorithm the context uses.
90+
91+
#### 4. Client:
92+
- creates a specific strategy object and passes it to the context.
93+
- The context exposes a setter which lets clients replace the strategy associated with the context at runtime.
94+
95+
**The context calls the execution method on the linked strategy object each time it needs to run the algorithm. The context doesn’t know what type of strategy it works with or how the algorithm is executed.**
96+
97+
---
98+
99+
### Components By geeksforgeeks
100+
101+
#### 1. Context
102+
- A class or object known as the Context
103+
- assigns the task to a strategy object
104+
- and contains a reference to it.
105+
- **The Context holds a reference to the selected strategy and delegates the task to it.**
106+
107+
- <details>
108+
<summary> <p style="display: inline;">More Details</p> </summary>
109+
110+
- It serves as an intermediary between the client and the strategy,
111+
- offering an integrated approach for task execution without exposing every detail of the process.
112+
- The Context maintains a reference to a strategy object and calls its methods to perform the task, allowing for interchangeable strategies to be used.
113+
114+
</details>
115+
116+
117+
#### 2. Strategy Interface
118+
- An abstract class or interface known as the Strategy Interface
119+
- specifies a set of methods that all concrete strategies must implement.
120+
- The Strategy Interface serves as a contract that defines a set of methods that all concrete strategies must implement.
121+
122+
123+
- <details>
124+
<summary> <p style="display: inline;">More Details</p> </summary>
125+
126+
- As a kind of agreement, it guarantees that all strategies follow the same set of rules and are interchangeable by the Context.
127+
- The Strategy Interface promotes flexibility and modularity in the design by establishing a common interface that enables decoupling between the Context and the specific strategies.
128+
</details>
129+
130+
131+
#### 3. Concrete Strategies
132+
- Concrete Strategies are the various implementations of the Strategy Interface.
133+
- Each concrete strategy provides a specific algorithm or behavior for performing the task defined by the Strategy Interface.
134+
135+
- <details>
136+
<summary> <p style="display: inline;">More Details</p> </summary>
137+
138+
- Concrete strategies encapsulate the details of their respective algorithms and provide a method for executing the task.
139+
- They are interchangeable and can be selected and configured by the client based on the requirements of the task.
140+
</details>
141+
142+
143+
#### 4. Client
144+
- The Client is responsible for
145+
- selecting and configuring the appropriate strategy
146+
- and providing it to the Context.
147+
- **The Client selects an appropriate strategy based on the task requirements and provides it to the Context**
148+
149+
- <details>
150+
<summary> <p style="display: inline;">More Details</p> </summary>
151+
152+
- It knows the requirements of the task and decides which strategy to use based on those requirements.
153+
- The client creates an instance of the desired concrete strategy and passes it to the Context,
154+
- enabling the Context to use the selected strategy to perform the task.
155+
</details>
156+
157+
158+
## What problems can it solve || When to Use || Use Cases
159+
160+
161+
### The Strategy Design Pattern can be useful in various scenarios, such as:
162+
163+
- Sorting algorithms:
164+
- Different sorting algorithms can be encapsulated into separate strategies and passed to an object that needs sorting.
165+
- Validation rules:
166+
- Different validation rules can be encapsulated into separate strategies and passed to an object that needs validation.
167+
- Text formatting:
168+
- Different formatting strategies can be encapsulated into separate strategies and passed to an object that needs formatting.
169+
- Database access:
170+
- Different database access strategies can be encapsulated into separate strategies and passed to an object that needs to access data from different sources.
171+
- Payment strategy:
172+
- Different payment methods can be encapsulated into separate strategies and passed to an object that needs to process payments.
173+
174+
175+
<details>
176+
<summary> <h3 style="display: inline;">geeksforgeeks</h3> </summary>
177+
178+
- **Multiple Algorithms**:
179+
- When you have multiple algorithms that can be used interchangeably based on different contexts, such as sorting algorithms
180+
- **Encapsulating Algorithms**:
181+
- When you want to encapsulate the implementation details of algorithms separately from the context that uses them,
182+
- **Runtime Selection**:
183+
- When you need to dynamically select and switch between different algorithms at runtime based on user preferences, configuration settings.
184+
- **Reducing Conditional Statements**:
185+
- When you have a class with multiple conditional statements that choose between different behaviors.
186+
- **Open and Closed**:
187+
- the Strategy pattern makes it easier to extend the system with new algorithms without modifying existing code.
188+
189+
</details>
190+
191+
<details>
192+
<summary> <h3 style="display: inline;">refactoring.guru</h3> </summary>
193+
194+
- When you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime.
195+
- When you have a lot of similar classes that only differ in the way they execute some behavior.
196+
- Use the pattern to isolate the business logic of a class from the implementation details of algorithms that may not be as important in the context of that logic.
197+
- When your class has a massive conditional statement that switches between different variants of the same algorithm.
198+
199+
</details>
200+
201+
202+
203+
## Examples
204+
205+
### Operations with context Example
206+
Source: https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm
207+
208+
<img style="background-color:#554777" src = "assets/strategy_pattern_uml_diagram.jpg">
209+
210+
- Context is a class which uses a Strategy.
211+
- In Main will use Context and strategy objects to demonstrate change in Context behavior based on strategy it deploys or uses.
212+
213+
214+
```dart
215+
///
216+
/// Step 1: Create an interface.
217+
abstract interface class Strategy {
218+
int doOperation(int num1, int num2);
219+
}
220+
221+
///
222+
/// Step 2: Create concrete classes implementing the same interface.
223+
224+
/// OperationAdd
225+
class OperationAdd implements Strategy {
226+
@override
227+
int doOperation(int num1, int num2) => num1 + num2;
228+
}
229+
230+
/// OperationSubtract
231+
class OperationSubtract implements Strategy {
232+
@override
233+
int doOperation(int num1, int num2) => num1 - num2;
234+
}
235+
236+
/// OperationMultiply
237+
class OperationMultiply implements Strategy {
238+
@override
239+
int doOperation(int num1, int num2) => num1 * num2;
240+
}
241+
242+
///
243+
/// Step 3: Create Context Class.
244+
class Context {
245+
final Strategy _strategy;
246+
247+
Context(Strategy strategy) : this._strategy = strategy;
248+
249+
int executeStrategy(int num1, int num2) {
250+
return _strategy.doOperation(num1, num2);
251+
}
252+
}
253+
254+
///
255+
/// Step 4: Use the Context to see change in behavior when it changes its Strategy.
256+
void main() {
257+
Context context = Context(OperationAdd());
258+
print("10 + 5 = " + "${context.executeStrategy(10, 5)}");
259+
260+
context = Context(OperationSubtract());
261+
print("10 - 5 = " + "${context.executeStrategy(10, 5)}");
262+
263+
context = Context(OperationMultiply());
264+
pri
265+
}
266+
267+
```
268+
### Sorting Example
269+
270+
Source: https://www.geeksforgeeks.org/strategy-pattern-set-1/
271+
272+
273+
<img style="background-color:#554777" src = "assets/geeks_strategy_dp.png">
274+
275+
```dart
276+
abstract interface class SortStrategy {
277+
List<int> sort(List<int> list);
278+
}
279+
280+
class BubbleSortStrategy implements SortStrategy {
281+
@override
282+
List<int> sort(List<int> list) {
283+
for (int i = 0; i < list.length; i++) {
284+
for (int j = 0; j < list.length - i - 1; j++) {
285+
if (list[j] > list[j + 1]) {
286+
int temp = list[j];
287+
list[j] = list[j + 1];
288+
list[j + 1] = temp;
289+
}
290+
}
291+
}
292+
return list;
293+
}
294+
}
295+
296+
class SelectionSortStrategy implements SortStrategy {
297+
@override
298+
List<int> sort(List<int> list) {
299+
for (int i = 0; i < list.length - 1; i++) {
300+
int minIndex = i;
301+
for (int j = i + 1; j < list.length; j++) {
302+
if (list[j] < list[minIndex]) {
303+
minIndex = j;
304+
}
305+
}
306+
int temp = list[minIndex];
307+
list[minIndex] = list[i];
308+
list[i] = temp;
309+
}
310+
return list;
311+
}
312+
}
313+
314+
class SortContext {
315+
SortStrategy _sortStrategy;
316+
317+
SortContext(SortStrategy sortStrategy) : _sortStrategy = sortStrategy;
318+
319+
void changeStrategy(SortStrategy sortStrategy) =>
320+
_sortStrategy = sortStrategy;
321+
322+
List<int> sort(List<int> list) {
323+
return _sortStrategy.sort(list);
324+
}
325+
}
326+
327+
void main() {
328+
// Create SortContext with BubbleSortStrategy
329+
SortContext sortContext = SortContext(BubbleSortStrategy());
330+
List<int> list1 = [5, 2, 9, 1, 5];
331+
sortContext.sort(list1);
332+
333+
// Change strategy to MergeSortStrategy
334+
sortContext.changeStrategy(SelectionSortStrategy());
335+
List<int> list2 = [8, 3, 7, 4, 2];
336+
sortContext.sort(list2);
337+
}
338+
339+
```
340+
341+
### Storage Data Source Example
342+
343+
- <strong><a href="storage_example.dart" target="_blank">Storage Data Source Example</a></strong>
344+
345+
346+
347+
### Payment Example
348+
349+
- /payment_example.dart
350+
- <strong><a href="storage_example.dart" target="_blank">Storage Data Source Example</a></strong>
351+
352+
353+
## Summery
354+
355+
- The Strategy Design Pattern is a powerful pattern in the world of object-oriented programming.
356+
- It provides a flexible way to encapsulate and swap the behavior of an object at runtime,
357+
- enabling code to be more adaptable and easier to maintain.
358+
359+
360+
## Sources
361+
362+
- https://www.freecodecamp.org/news/a-beginners-guide-to-the-strategy-design-pattern/
363+
- https://www.geeksforgeeks.org/strategy-pattern-set-1/
364+
- https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm
365+
- https://refactoring.guru/design-patterns/strategy
366+
367+
368+
<p align="right">(<a href="#top">back to top</a>)</p>
1.11 MB
Loading
21.3 KB
Loading
24.1 KB
Loading

0 commit comments

Comments
 (0)