我经常看到人们说"如果你需要朋友/内部然后你的设计是错误的",有人可以告诉我如何重新设计以下代码以消除ChessPiece.Location中的内部?
它目前被使用,因此向ChessBoard添加一个片段设置ChessPiece.Location属性以匹配,显然使它公开将比内部更糟糕并使其私有将阻止ChessBoard更新位置.感谢您的任何见解.
public struct Coord
{
public Coord(int x, int y) { this.X = x; this.Y = y; }
public int X { get; private set; }
public int Y { get; private set; }
}
public class ChessBoard
{
public ChessBoard() { /*[...]*/ }
public ChessPiece this[int x, int y]
{
get
{
// Return ChessPiece at this position (or null)
}
set
{
// Add ChessPiece at this position and set its Location property
}
}
public class ChessPiece
{
public ChessPiece() { /*[...]*/ }
public Coord Location { get; internal set; }
}
Run Code Online (Sandbox Code Playgroud)
我个人认为ChessPiece知道它的位置很奇怪 - 这似乎是ChessBoard的功能,而不是作品本身.(从棋盘上取下棋子后,它的位置是什么位置?它通常仍然是有效的棋子......)
我将位置/移动逻辑放入ChessBoard,并存储Dictionary<ChessPiece, Coord>每个有效棋子的位置.