1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace NetSnippetsQuickTest
{
public interface IFilter<T>
{
IEnumerator<T> Apply(IEnumerator<T> input);
}
//test impl to sho usage
public abstract class FilterBase<T>: IFilter<T>
{
public IEnumerator<T> Apply(IEnumerator<T> input)
{
while (input.MoveNext())
{
yield return processElement(input.Current);
}
yield break;
}
protected abstract T processElement(T o);
}
public class Pipeline<T>
{
private readonly List<IFilter<T>> _filter;
private bool _isExecuting = false;
public Pipeline(List<IFilter<T>> filter)
{
_filter = filter;
}
public IEnumerator<T> Execute(IEnumerator<T> input)
{
_isExecuting = true;
IEnumerator<T> currentInput = input;
//call all filter which are chained together via yield
foreach (IFilter<T> filter in _filter)
{
currentInput = filter.Apply(currentInput);
}
_isExecuting = false;
//return enumerator of last filter
return currentInput;
}
}
}
//-- sample unit test
[TestFixture]
public class _Tests
{
private class TestFilter : FilterBase<string>
{
public static int instanceCount = 0;
private int instanceID;
public TestFilter()
{
instanceID = instanceCount++;
}
protected override string processElement(string o)
{
return string.Format("{0}->{1}", o, instanceID);
}
}
[Test]
public void TestPipeline()
{
Pipeline<string> pipeline;
int filterCount = 10;
List<IFilter<string>> filter = new List<IFilter<string>>();
List<string> input = new List<string>();
for (int i = 0; i < filterCount; i++)
{
filter.Add(new TestFilter());
input.Add(string.Format("Input{0}_", i));
}
pipeline = new Pipeline<string>(filter);
IEnumerator<string> enumerator = pipeline.Execute(input.GetEnumerator());
while (enumerator.MoveNext())
{
Console.Out.WriteLine(enumerator.Current);
}
}
}
}
/*
* output
Input0_->0->1->2->3->4->5->6->7->8->9
Input1_->0->1->2->3->4->5->6->7->8->9
Input2_->0->1->2->3->4->5->6->7->8->9
Input3_->0->1->2->3->4->5->6->7->8->9
Input4_->0->1->2->3->4->5->6->7->8->9
Input5_->0->1->2->3->4->5->6->7->8->9
Input6_->0->1->2->3->4->5->6->7->8->9
Input7_->0->1->2->3->4->5->6->7->8->9
Input8_->0->1->2->3->4->5->6->7->8->9
Input9_->0->1->2->3->4->5->6->7->8->9
*/
|