Add strategy pattern example, count without loop or if

This commit is contained in:
Petrutiu Mihai
2016-07-05 09:21:08 +03:00
parent aeaa1b627d
commit c174b23929
4 changed files with 58 additions and 1 deletions

View File

@@ -27,6 +27,8 @@ namespace BehavioralPatterns
Console.Write("4: Command Pattern\r\n");
Console.Write("5: Mediator Pattern\r\n");
Console.Write("6: Memento Pattern\r\n");
Console.Write("7: State Pattern\r\n");
Console.Write("8: Strategy Pattern\r\n");
Console.Write("0: exit\r\n>");
var key = Console.ReadKey();
@@ -54,6 +56,12 @@ namespace BehavioralPatterns
case '6':
MementoPatternExamples.Run();
break;
case '7':
StatePatternExamples.Run();
break;
case '8':
StrategyPatternExamples.Run();
break;
}
if (key.KeyChar == '0')
break;

View File

@@ -28,7 +28,8 @@ namespace IteratorPattern
public static string GetPatternDescription()
{
return @"Pattern description:
In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.
In object-oriented programming, the iterator pattern is a design pattern in which an iterator
is used to traverse a container and access the container's elements.
C# interfaces helpers for Iterator pattern: IEnumerator<T>, IEnumerable<T>, yield for creating IEnumerable<T>
Java: Iterator<E>, Iterable<E>";
}

View File

@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StrategyPattern.LoopWithException
{
public class LoopWithExceptionExample
{
public static void Run()
{
LoopUsingException loopUsingException = new LoopUsingException(40, (i) => Console.WriteLine(i));
loopUsingException.ExecuteForAll();
}
}
public class LoopUsingException
{
private Action<int> executeStrategy;
private int repeatCount;
public LoopUsingException(int repeatCount, Action<int> executeStrategy)
{
this.repeatCount = repeatCount;
this.executeStrategy = executeStrategy;
}
public void ExecuteForAll(int index = 1)
{
//Stop condition
try
{
var x = 1 / (repeatCount + 1 - index);
}
catch (DivideByZeroException)
{
return;
}
executeStrategy(index);
ExecuteForAll(++index);
}
}
}

View File

@@ -1,4 +1,5 @@
using StrategyPattern.ArrangeInterview;
using StrategyPattern.LoopWithException;
using StrategyPattern.ShippingCalculator;
using System;
using System.Collections.Generic;
@@ -14,6 +15,7 @@ namespace StrategyPattern
{
public static void Run()
{
LoopWithExceptionExample.Run();
ArrangeInterviewMotivationalExample.Run(InterviewPersons.Get());