Skip to content

Instantly share code, notes, and snippets.

@ralfw
Last active December 22, 2015 05:29
Show Gist options
  • Save ralfw/6424273 to your computer and use it in GitHub Desktop.
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.
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));
}
}
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