How to group generic classes?
I am working on a generic game engine for simple board games and such. I am defining interfaces that I will require each game to implement I have classes like IGame, IGameState, IBoardEvaluator, and IMove.
I have methods like IGame.PerformMove(IMove move), that I would like to restrict. If I am playing tic-tac-toe I would like to enforce that I can only use the concrete classes TTTGame, TTTState, TTTMove, etc...
I can think of several ways to do this, but none of them sound fun. Maybe all classes could have a single generic parameter, and I could make sure it matches.
so IGame<T> has method PerformMove(IMove<T> move)
If that works out, I wouldn't know what class to use for T. Maybe it doesn't matter.
My other idea is put a bunch of generic parameters on IGame and give it all of the classes I need. 开发者_开发技巧So I would create class TTTGame<TTTMove,TTTState,TTTMove....>
That isn't pretty either. Is there a common pattern to do this?
I dont see what advantage you get from specifying that your TTTGame class can only take TTTMoves.
I think you might be over engineering here.
The only thing you are protecting yourself from by doing that is some rogue MonopolyMove class becoming self-aware and putting itself in your code.
I say stick with the interface definitions and avoid the generics unless you have a really valid case. I dont see one based on what you have mentioned.
The whole point of interfaces is to not care about the concrete implementation of the class. Hence I don't see a need to directly enforce only a certain class, in that case an argument could be made to just pass the class itself.
Such as
TTTGame : IGame
{
PerformMove(TTTMove move);
}
Perhaps this is what you are talking about.
public interface IGame<T> where T:IMove
{
void PerformMove(T move);
}
public class TTTGame : IGame<TTTMove>
{
public void PerformMove(TTTMove move)
{
//perform move
}
}
Now your IGame is forced to take an IMove, but like you said..with more classes like (IState..etc) this will get messy quick.
I'd say that the fact that you're feeling a need to restrict the implementation of your interfaces to certain classes is an indication of the interfaces not being specific enough.
Is IGame really a good idea in the first place? The name indicates that it could be equally valid for tic-tac-toe and Quake. Sure, there are some similarities between different board games (such as performing moves), but will you really benefit from creating an abstraction at that high level?
加载中,请稍侯......
精彩评论