棋子层次结构设计:继承与类型字段 [英] Chess piece hierarchy design: inheritance vs type fields
问题描述
我有件的基类
class piece;
和包含派生对象的数组
piece* board[8][8];
通过虚拟功能实现优势,简洁设计。缺点,如果我必须在板上找到一块或比较一件我必须恢复到动态铸造(或typeid)。它是丑陋的,并且在制作数百万个请求时可能会很糟糕。
Advantage, clean design through virtual functions. Disadvantage, if I have to find a piece in the board or compare a piece I have to revert to dynamic casting (or typeid). It’s ugly and could be a performance hog when making millions of requests.
另一方面,如果我创建一个单件类的数组,那么它有一个类型字段为了识别件,我没有这个问题(它应该更快)但我必须制作超级丑陋的switch语句。我想,由于件数是有限的,我不认为自己制造了那么多开关,这可能最终是一个更好的选择,你觉得怎么样?
In the other hand, if I make an array of a single piece class, that has a type field for identifying pieces, I don’t have this problem (and it should be faster) but I have to make super ugly switch statements. I guess that since the number of pieces is finite and I don’t see myself making that many of switches, this could be in the end a better choice, what do you think?
这是为了好玩(所以没有位线)。
This is for fun (so no bitboard).
编辑1
阅读一些答案,我认为仅使用类型字段进行运算符重载(==,!= ...)可以带来两个单词中最好的。
Reading some answers, I think using type fields only for operator overloading (==,!=...) could bring the best of both words.
提升:: variant看起来也很有趣。
The boost::variant looks very interesting too.
推荐答案
我会选择类层次结构。
为了找到一件作品,你可以为每件作品保留一份单独的清单。所以你知道在哪里寻找每一种类型。
For finding a piece you can keep a separeted list for each piece type. So you know where to look for each piece type.
为了比较你也可以依赖虚拟方法。
For comparison you can rely on virtual methods too.
另一个方法是使用组件架构(如下所述: http:// cowboyprogramming.com/2007/01/05/evolve-your-heirachy/ ),但我认为这对于国际象棋游戏来说太过分了,你可以清楚地知道这些类型并知道这些类型不会很快改变:) 。
Another aproach is to use a component architecture (like described here: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/), but I think it is too much for a chess game where you clealy know the types and know that those types will not change soon :).
这篇关于棋子层次结构设计:继承与类型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!