我正在制作国际象棋程序,我正在尝试优化我的代码,其中我有一个抽象基类ChessPiece
,它具有基本属性Board
,Color
和StartPosition
。现在,在这个基类构造函数中,我添加了实例化的特定部分。这是那部分:
// ChessPiece.cs
protected ChessPiece(Square startPosition, PieceColor color, Board board)
{
this.StartPosition = startPosition;
this.CurrentPosition = startPosition;
this.Color = color;
this.Board = board;
this.Board[startPosition] = this;
// ↑
// I add the pieces inside the indexer assignment (e.g. pieces.Add(piece)...)
}
以下是我在Board
类中添加各个部分的方法:
// Board.cs
public ChessPiece this[Square square]
{
get { ... }
set
{
// simplified version of how I add pieces
this._pieces.Add(value);
}
}
现在,我以这种方式设置我的电路板:
// Game.cs
private void PopulateBoard()
{
this.CreateStandardPieces(PieceColor.White);
this.CreateStandardPieces(PieceColor.Black);
}
private void CreateStandardPieces(PieceColor color)
{
// rook
new Rook(aSquare, color, this.Board);
// more initializations here
}
样本实例化new Rook(...)
对我来说很奇怪,就像它是一个空的实例化。实际发生的事情是每当我实例化一个片段时,它会自动添加到电路板上,而不是查看“空实例化”。
现在我的问题是,我应该如何改进我的设计以避免实例化看起来像这样?或者,这种设计是否被认为是一种优秀的OOP设计?
编辑: 添加了关于如何添加碎片的代码
您可以将电路板视为一个系统,将其作为子系统。它关注和耦合的奇怪分离让子系统知道父系统,甚至改变它的状态。
在我看来,一种更清洁的方式是电路板添加件(或板上方的系统)。
阅读Separations of concerns
和High cohesion – Low coupling
编辑:这件作品应该只保存有关如何在棋盘上移动的信息。它可以通过电路板或电路板上方的系统实际移动它