Skip to content

Instantly share code, notes, and snippets.

@solebox
Created November 2, 2016 22:21
Show Gist options
  • Save solebox/f4924a8a10954aff962d92601aae8c98 to your computer and use it in GitHub Desktop.
Save solebox/f4924a8a10954aff962d92601aae8c98 to your computer and use it in GitHub Desktop.
using System;
2
3 public class Program
4 {
5 public static void Main()
6 {
7 CalculateClient client = new CalculateClient();
8
9 client.SetCalculate(new Minus());
10 Console.WriteLine("Minus: " + client.Calculate(7, 1));
11
12 client.SetCalculate(new Plus());
13 Console.WriteLine("Plus: " + client.Calculate(7, 1));
14 }
15 }
16
17 //The interface for the strategies
18 public interface ICalculate
19 {
20 int Calculate(int value1, int value2);
21 }
22
23 //strategies
24 //Strategy 1: Minus
25 public class Minus : ICalculate
26 {
27 public int Calculate(int value1, int value2)
28 {
29 return value1 - value2;
30 }
31 }
32
33 //Strategy 2: Plus
34 public class Plus : ICalculate
35 {
36 public int Calculate(int value1, int value2)
37 {
38 return value1 + value2;
39 }
40 }
41
42 //The client
43 public class CalculateClient
44 {
45 private ICalculate strategy;
46
47 //Executes the strategy
48 public int Calculate(int value1, int value2)
49 {
50 return strategy.Calculate(value1, value2);
51 }
52
53 //Change the strategy
54 public void SetCalculate(ICalculate strategy){
55 this.strategy = strategy;
56 }
57 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment