Skip to content

Instantly share code, notes, and snippets.

@mikeobrien
Created November 14, 2012 16:23
Show Gist options
  • Save mikeobrien/4073094 to your computer and use it in GitHub Desktop.
Save mikeobrien/4073094 to your computer and use it in GitHub Desktop.
Simple Behavior Graph
public interface IBehavior
{
void Execute<T>(T data);
}
public class BehaviorGraph
{
private readonly IList<Type> _behaviors = new List<Type>();
public T Execute<T>()
{
return Execute(default(T));
}
public T Execute<T>(Func<IBehavior, Type, IBehavior> factory)
{
return Execute(default(T), factory);
}
public T Execute<T>(T data)
{
return Execute(data, (b, t) => (IBehavior)Activator.CreateInstance(t, new object[] {b}));
}
public T Execute<T>(T data, Func<IBehavior, Type, IBehavior> factory)
{
var result = new ResultBehavior();
_behaviors.Aggregate(result, factory).Execute(data);
return (T)result.Data;
}
public BehaviorGraph WrapBehavior<TBehavior>() where TBehavior : IBehavior
{
_behaviors.Add(typeof(TBehavior));
return this;
}
private class ResultBehavior : IBehavior
{
public object Data { get; private set; }
public void Execute<T>(T data)
{
Data = data;
}
}
}
[TestFixture]
public class BehaviorGraphTests
{
private class Behavior : IBehavior
{
private readonly IBehavior _innerBehavior;
private readonly string _value;
public Behavior(IBehavior innerBehavior, string value)
{ _innerBehavior = innerBehavior; _value = value; }
public void Execute<T>(T data) { _innerBehavior.Execute(data + _value); }
}
private class Behavior1 : Behavior
{ public Behavior1(IBehavior innerBehavior) : base(innerBehavior, "1") { } }
private class Behavior2 : Behavior
{ public Behavior2(IBehavior innerBehavior) : base(innerBehavior, "2") { } }
private class Behavior3 : Behavior
{ public Behavior3(IBehavior innerBehavior) : base(innerBehavior, "3") { } }
[Test]
public void should_execute_behaviors_in_order()
{
new BehaviorGraph()
.WrapBehavior<Behavior2>()
.WrapBehavior<Behavior1>()
.WrapBehavior<Behavior3>()
.Execute("hai")
.ShouldEqual("hai312");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment