扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
意图
保证一个类只有一个实例,并提供访问它的全局访问点。
场景
我们现在要做一个网络游戏的服务端
需要考虑的问题是,即使在多线程的并发状态下,用户只能通过一个唯一的入口来分配,由此引入了Singleton模式来实现这个唯一的入口。
示例代码
以下是引用片段: using System; using System.Collections.Generic; using System.Threading; namespace SingletonExample { class Program { static void Main(string[] args) { ParameterizedThreadStart ts = new ParameterizedThreadStart(EnterPlayer); for (int i = 0; i < 20; i++) { Thread t = new Thread(ts); t.Start("player" + i); } LoadBalanceServer.GetLoadBalanceServer().ShowServerInfo(); } static void EnterPlayer(object playerName) { LoadBalanceServer lbs = LoadBalanceServer.GetLoadBalanceServer(); lbs.GetLobbyServer().EnterPlayer(playerName.ToString()); } } class LoadBalanceServer { private const int SERVER_COUNT = 3; private List serverList = new List(); private static volatile LoadBalanceServer lbs; private static object syncLock = new object(); public LoadBalanceServer() { for (int i = 0; i < SERVER_COUNT; i++) { serverList.Add(new LobbyServer("LobbyServer" + i)); } } public static LoadBalanceServer GetLoadBalanceServer() { if (lbs == null) { lock (syncLock) { if (lbs == null) { Thread.Sleep(100); lbs = new LoadBalanceServer(); } } } return lbs; } public LobbyServer GetLobbyServer() { LobbyServer ls = serverList[0]; for (int i = 1; i < SERVER_COUNT; i++) { if (serverList[i].PlayerList.Count < ls.PlayerList.Count) ls = serverList[i]; } return ls; } public void ShowServerInfo() { foreach (LobbyServer ls in serverList) { Console.WriteLine("=================" + ls.ServerName + "================="); foreach (string player in ls.PlayerList) { Console.WriteLine(player); } } } } class LobbyServer { private List playerList = new List(); public List PlayerList { get { return playerList; } } private string serverName; public string ServerName { get { return serverName; } } public LobbyServer(string serverName) { this.serverName = serverName; } public void EnterPlayer(string playerName) { playerList.Add(playerName); } } } |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者