forked from EdisonTalk/DesignPattern.Samples.CSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoadBalancer.cs
82 lines (74 loc) · 2.26 KB
/
LoadBalancer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Manulife.ChengDu.DesignPattern.Singleton
{
/// <summary>
/// 假装自己是一个负载均衡器
/// </summary>
public class LoadBalancer
{
// 私有静态变量,存储唯一实例
//private static LoadBalancer instance = null;
//private static readonly LoadBalancer instance = new LoadBalancer();
//private static readonly object syncLocker = new object();
// 服务器集合
private IList<CustomServer> serverList = null;
// 私有构造函数
private LoadBalancer()
{
serverList = new List<CustomServer>();
}
// 公共静态成员方法,返回唯一实例
public static LoadBalancer GetLoadBalancer()
{
// 第一重判断
//if (instance == null)
//{
// // 锁定代码块
// lock (syncLocker)
// {
// // 第二重判断
// if (instance == null)
// {
// instance = new LoadBalancer();
// }
// }
//}
//return instance;
return Nested.instance;
}
// 使用内部类+静态构造函数实现延迟初始化
class Nested
{
static Nested() { }
internal static readonly LoadBalancer instance = new LoadBalancer();
}
// 添加一台Server
public void AddServer(CustomServer server)
{
serverList.Add(server);
}
// 移除一台Server
public void RemoveServer(string serverName)
{
foreach (var server in serverList)
{
if (server.Name.Equals(serverName))
{
serverList.Remove(server);
break;
}
}
}
// 获得一台Server - 使用随机数获取
private Random rand = new Random();
public CustomServer GetServer()
{
int index = rand.Next(serverList.Count);
return serverList[index];
}
}
}