ermöglicht das sequentielle bearbeiten von input elementen in einer pipeline durch anwendung von filtern. geeignet für zeitintensive elementbezogene operationen
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
*/
Kommentare zum Snippet