1: namespace DoFactory.GangOfFour.Singleton.RealWorld { // MainApp test application
2: class MainApp { static void Main()
3: {
4: LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
5: LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
6: LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
7: LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
8: // Same instance?
9: if (b1 == b2 && b2 == b3 && b3 == b4)
10: {
11: Console.WriteLine("Same instance/n");
12: }
13: // All are the same instance -- use b1 arbitrarily
14: // Load balance 15 server requests
15: for (int i = 0; i < 15; i++)
16: {
17: Console.WriteLine(b1.Server);
18: }
19: // Wait for user
20: Console.Read();
21: }
22: }
23: //"Singleton"
24: class LoadBalancer
25: {
26: private static
27: LoadBalancer instance;
28: private ArrayList servers = new ArrayList();
29: private Random random = new Random();
30: // Lock synchronization object private static
31: object syncLock = new object();
32: // Constructor (protected)
33: protected LoadBalancer()
34: {
35: // List of available servers
36: servers.Add("ServerI");
37: servers.Add("ServerII");
38: servers.Add("ServerIII");
39: servers.Add("ServerIV");
40: servers.Add("ServerV");
41: }
42: public static LoadBalancer GetLoadBalancer()
43: {
44: //Support multithreaded applications through
45: // 'Double checked locking' pattern which (once
46: // the instance exists) avoids locking each
47: // time the method is invoked
48: if (instance == null)
49: {
50: lock (syncLock)
51: {
52: if (instance == null)
53: {
54: instance = new LoadBalancer();
55: }
56: }
57: }
58: return instance;
59: }
60: // Simple, but effective random load balancer
61: public string Server
62: {
63: get { int r = random.Next(servers.Count); return servers[r].ToString();
64: }
65: }
66: }
67: }