Created
November 14, 2012 16:23
-
-
Save mikeobrien/4073094 to your computer and use it in GitHub Desktop.
Simple Behavior Graph
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 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; | |
} | |
} | |
} |
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
[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