让我们使用这个简单的例子:
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];
}
}
Box.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 }
}
}
有没有什么好的设计模式可以让它更优雅?
最佳答案
您可以使用多种策略。
针对接口(interface)进行编程通常很有用。下面的 IBox 界面不允许人们编辑框(不将其转换为 Box
),但仍然让您的代码保持简单。
public class Connect4Board
{
private Box[,] _boxes = new Box[7, 6];
public void DropPieceAt(int column, bool redPiece)
{
//Safe modifications to box colors.
}
public IBox GetBoxAt(int x, int y)
{
return _boxes[x, y];
}
}
public interface IBox
{
bool IsRed { get; }
bool IsEmpty { get; }
}
public class Box : IBox
{
public bool IsRed { get; set; }
public bool IsEmpty { get; set; }
}
另一种方法是使盒子始终不可变(如字符串),而不是修改盒子的状态,您只需修改数组中哪个盒子位于哪个位置:
public class Connect4Board
{
private Box[,] _boxes = new Box[7, 6];
public Connect4Board()
{
for(int i = 0; i<7; i++)
{
for(int j = 0; j<6; j++)
{
// Notice how you're not changing a color, but assigning the location
_boxes[i,j] = Box.Empty;
}
}
}
public void DropPieceAt(int column, bool redPiece)
{
// Modifications to the top empty location in the given column.
}
public Box GetBoxAt(int x, int y)
{
return _boxes[x, y];
}
}
public class Box
{
public bool IsRed { get; private set; }
public bool IsBlack { get; private set; }
public bool IsEmpty { get; private set; }
private Box() {}
public static readonly Box Red = new Box{IsRed = true};
public static readonly Box Black = new Box{IsBlack = true};
public static readonly Box Empty = new Box{IsEmpty = true};
}
关于c# - 私有(private)成员访问的设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16424518/