Created
July 9, 2011 21:09
-
-
Save jmarnold/1073964 to your computer and use it in GitHub Desktop.
Compositional Patterns: Policies
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 DefaultPolicy : IPolicy | |
{ | |
public bool Matches() | |
{ | |
return true; | |
} | |
public void Execute() | |
{ | |
// default behavior | |
} | |
} |
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 IPolicy | |
{ | |
bool Matches(); | |
void Execute(); | |
} |
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 PolicyConsumer | |
{ | |
private readonly IEnumerable<IPolicy> _policies; | |
public PolicyConsumer(IEnumerable<IPolicy> policies) | |
{ | |
var configuredPolicies = new List<IPolicy>(); | |
configuredPolicies.AddRange(policies); | |
configuredPolicies.Add(new DefaultPolicy()); // make sure this is last | |
_policies = configuredPolicies; | |
} | |
public void Execute() | |
{ | |
var policy = _policies | |
.FirstOrDefault(p => p.Matches()); | |
if(policy == null) | |
{ | |
// throw, log, etc. | |
return; | |
} | |
policy.Execute(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment