您想控制对象的创建,这对于工厂模式来说是一项完美的工作!
您可以创建一个包含这些值的集合,将构造函数设为私有并创建一个包含全局玩家数据的静态变量:
public class Player
{
// For access
public static IEnumerable<Player> Players { get; private set; }
public int Id { get; private set; }
// Private constructor
private Player(int Id)
{
this.Id = Id;
}
// Factory method
public static void CreatePlayers(int NumPlayers)
{
// Only create players collection once!
if (Players != null)
throw new InvalidOperationException();
Players = new List<Player>(NumPlayers);
for (int i = 0; i < NumPlayers; i++)
{
var player = new Player(i);
player.Players = Players;
Players.Add(player);
}
}
public void DoStuff()
{
// ...
}
}
即使这是 C#,也应该很容易将其转换为 CLI/C++。确保您还将复制构造函数声明为私有。其他答案也提到了internal
访问器,但我个人试图阻止使用,internal
因为它打破了传统的 OOP 设计。