From 31257994a2ef90a4321a0a056d4dd179631dab2f Mon Sep 17 00:00:00 2001 From: Petrutiu Mihai Date: Tue, 5 Jul 2016 12:47:36 +0300 Subject: [PATCH] Implement loop without if/loop --- .../LoopWithoutLoop/MagnificLoopExample.cs | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/StrategyPattern/LoopWithoutLoop/MagnificLoopExample.cs diff --git a/src/StrategyPattern/LoopWithoutLoop/MagnificLoopExample.cs b/src/StrategyPattern/LoopWithoutLoop/MagnificLoopExample.cs new file mode 100644 index 0000000..025a7e2 --- /dev/null +++ b/src/StrategyPattern/LoopWithoutLoop/MagnificLoopExample.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace StrategyPattern.LoopWithoutLoop +{ + public class MagnificLoopExample + { + public static void Run() + { + LoopLikeABoss loopLikeABoss = new LoopLikeABoss(); + loopLikeABoss.PrintNumbersOf1ToN(10); + } + } + + public class LoopLikeABoss + { + public void PrintNumbersOf1ToN(int n) + { + LoopStep l = new LoopStep((i) => Console.WriteLine(i)); + l.Loops = new LoopStep[] { l, new StopLoopStep() }; + l.Loop(1, n); + } + } + + public class LoopStep + { + Action printNumber; + public LoopStep(Action printNumber) + { + this.printNumber = printNumber; + } + public LoopStep[] Loops { get; set; } + + + + public virtual void Loop(int currentIndex, int n) + { + var loopStep = GetNextStep(currentIndex, n); + loopStep.printNumber(currentIndex); + loopStep.Loop(++currentIndex, n); + } + + public LoopStep GetNextStep(int i, int n) + { + return Loops[i/n]; + } + } + + public class StopLoopStep : LoopStep + { + public StopLoopStep() : base((i) => { }) + { + } + + public override void Loop(int currentIndex, int n) + { + return; + } + } + + +}