Skip to content

Commit 7993d59

Browse files
committed
Strategy Pattern example
1 parent 7d15fb9 commit 7993d59

File tree

1 file changed

+28
-32
lines changed

1 file changed

+28
-32
lines changed

README.md

Lines changed: 28 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2065,60 +2065,56 @@ Wikipedia says
20652065
Translating our example from above. First of all we have our strategy interface and different strategy implementations
20662066

20672067
```C#
2068-
interface SortStrategy
2068+
interface ISortStrategy
20692069
{
2070-
public function sort(array $dataset): array;
2070+
List<int> Sort(List<int> dataset);
20712071
}
20722072

2073-
class BubbleSortStrategy implements SortStrategy
2073+
class BubbleSortStrategy : ISortStrategy
20742074
{
2075-
public function sort(array $dataset): array
2076-
{
2077-
echo "Sorting using bubble sort";
2078-
2079-
// Do sorting
2080-
return $dataset;
2081-
}
2075+
public List<int> Sort(List<int> dataset)
2076+
{
2077+
Console.WriteLine("Sorting using Bubble Sort !");
2078+
return dataset;
2079+
}
20822080
}
20832081

2084-
class QuickSortStrategy implements SortStrategy
2082+
class QuickSortStrategy : ISortStrategy
20852083
{
2086-
public function sort(array $dataset): array
2087-
{
2088-
echo "Sorting using quick sort";
2089-
2090-
// Do sorting
2091-
return $dataset;
2092-
}
2084+
public List<int> Sort(List<int> dataset)
2085+
{
2086+
Console.WriteLine("Sorting using Quick Sort !");
2087+
return dataset;
2088+
}
20932089
}
20942090
```
20952091

20962092
And then we have our client that is going to use any strategy
20972093
```C#
20982094
class Sorter
20992095
{
2100-
protected $sorter;
2096+
private readonly ISortStrategy mSorter;
21012097

2102-
public function __construct(SortStrategy $sorter)
2103-
{
2104-
$this->sorter = $sorter;
2105-
}
2098+
public Sorter(ISortStrategy sorter)
2099+
{
2100+
mSorter = sorter;
2101+
}
21062102

2107-
public function sort(array $dataset): array
2108-
{
2109-
return $this->sorter->sort($dataset);
2110-
}
2103+
public List<int> Sort(List<int> unSortedList)
2104+
{
2105+
return mSorter.Sort(unSortedList);
2106+
}
21112107
}
21122108
```
21132109
And it can be used as
21142110
```C#
2115-
$dataset = [1, 5, 4, 3, 2, 8];
2111+
var unSortedList = new List<int> { 1, 10, 2, 16, 19 };
21162112

2117-
$sorter = new Sorter(new BubbleSortStrategy());
2118-
$sorter->sort($dataset); // Output : Sorting using bubble sort
2113+
var sorter = new Sorter(new QuickSortStrategy());
2114+
sorter.Sort(unSortedList); // // Output : Sorting using Bubble Sort !
21192115
2120-
$sorter = new Sorter(new QuickSortStrategy());
2121-
$sorter->sort($dataset); // Output : Sorting using quick sort
2116+
sorter = new Sorter(new QuickSortStrategy());
2117+
sorter.Sort(unSortedList); // // Output : Sorting using Quick Sort !
21222118
```
21232119

21242120
💢 State

0 commit comments

Comments
 (0)