让我们使用这个简单的例子:
Connect4Board.cs:
public class Connect4Board
{
private Box[,] _boxes = new Box[7, 6];
public void DropPieceAt(int column, bool redPiece)
{
//Safe modifications to box colors.
}
public Box GetBoxAt(int x, int y)
{
return _boxes[x, y];
}
}
盒子.cs:
public class Box
{
public bool IsRed { get; private set; }
public bool IsEmpty { get; private set; }
}
我想GetBoxAt()
返回一个带有只读属性的框。但是我希望我Connect4Board
能够改变盒子的颜色。
假设我根本不想使用internal
修饰符。
我的解决方案(很丑):
public class Connect4Board
{
private Box.MutableBox[,] _mutableBoxes = new Box.MutableBox[7, 6];
public Connect4Board()
{
for (int y = 0; y < 6; y++)
{
for (int x = 0; x < 7; x++)
{
_mutableBoxes[x, y] = new Box.MutableBox();
}
}
}
public void DropPieceAt(int column, bool isRed)
{
//Safe modifications to box colors.
}
public Box GetBoxAt(int x, int y)
{
return _mutableBoxes[x, y].Box;
}
}
public class Box
{
public bool IsRed { get; private set; }
public bool IsEmpty { get; private set; }
private Box()
{
}
public class MutableBox
{
public Box Box { get; private set; }
public MutableBox()
{
Box = new Box();
}
public void MakeRed() { //I can modify Box here }
public void MakeYellow() { //I can modify Box here }
public void MakeEmpty() { //I can modify Box here }
}
}
有没有一个好的设计模式可以让它更优雅?