Last active
December 22, 2015 05:29
-
-
Save ralfw/6424273 to your computer and use it in GitHub Desktop.
Pipes and filters à la Steve Bate. No, wait, it´s not pipes and filters anymore. It´s an assembly line processing work pieces. And you can assemble the assembly line using the + operator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AssemblyLineFor<T> | |
{ | |
public interface IFilter | |
{ | |
T Process(T message); | |
} | |
private readonly IList<Func<T, T>> _stages = new List<Func<T, T>>(); | |
public static AssemblyLineFor<T> operator +(AssemblyLineFor<T> assemblyLine, IFilter singletonFilter) | |
{ | |
return assemblyLine.Register(singletonFilter); | |
} | |
public static AssemblyLineFor<T> operator +(AssemblyLineFor<T> assemblyLine, Type perMessageFilterType) | |
{ | |
return assemblyLine.Register(perMessageFilterType); | |
} | |
public static AssemblyLineFor<T> operator +(AssemblyLineFor<T> assemblyLine, Func<T, T> filter) | |
{ | |
return assemblyLine.Register(filter); | |
} | |
protected AssemblyLineFor<T> Register(IFilter singletonFilter) | |
{ | |
_stages.Add(singletonFilter.Process); | |
return this; | |
} | |
protected AssemblyLineFor<T> Register(Type perMessageFilterType) | |
{ | |
_stages.Add(msg => { | |
var f = Activator.CreateInstance(perMessageFilterType) as IFilter; | |
return f.Process(msg); | |
}); | |
return this; | |
} | |
protected AssemblyLineFor<T> Register(Func<T, T> filter) | |
{ | |
_stages.Add(filter); | |
return this; | |
} | |
public T Process(T message) | |
{ | |
return _stages.Aggregate(message, (current, stage) => stage(current)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main() | |
{ | |
var a = new AssemblyLineFor<string>(); | |
a = a + new SingletonFilter3() | |
+ typeof(PerMessageFilter3) | |
+ (msg => msg + "L;"); | |
var result = a.Process("world:"); | |
Console.WriteLine(result); | |
} | |
} | |
class SingletonFilter3 : AssemblyLineFor<string>.IFilter | |
{ | |
public string Process(string message) | |
{ | |
return message + "SF" + this.GetHashCode() + ";"; | |
} | |
} | |
class PerMessageFilter3 : AssemblyLineFor<string>.IFilter | |
{ | |
public string Process(string message) | |
{ | |
return message + "PMF" + this.GetHashCode() + ";"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment