I have a case where I have some classes that each process a type of token. They all descend from a base handler class (simplified down a bit, so excuse any anti-compile typos):
public abstract class TokenClassBase { public static bool HandlesTokenType(TokenKind AType) { return handledTokens.Contains(AType); } protected virtual void HandleToken(AToken) { } } public class TokenClass1 : TokenClassBase { public static new bool HandlesTokenType(TokenKind AKind) { return AKind == TokenKind.type1; } public override void HandleToken(AToken) { //do some work } } // public class TokenClass2... etc I also have a worker class where I'd like to store a list of these handlers, and later instantiate one of the handlers to process a token:
public class MyWorker { private List<Type> handlers; public MyWorker() { handlers = new List<Type>; handlers.Add(typeof(TokenClass1)); handlers.Add(typeof(TokenClass2)); //... etc } protected virtual void HandleToken(AToken) { foreach (TokenBaseClass handler in handlers) { if (handler.HandlesToken(AToken)) { instantiate(handler); handler.HandleToken(AToken); break; } } } } My question is, how do I handle the last foreach? Is this even possible - or is there a better way? I like the extensibility of being able to add new types in the future, just by adding them to the handlers list (or even passing them in from outside). I'm using c#, framework 3.5+.