-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathSingletonPatternExample1.cs
More file actions
65 lines (57 loc) · 1.99 KB
/
SingletonPatternExample1.cs
File metadata and controls
65 lines (57 loc) · 1.99 KB
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
//-------------------------------------------------------------------------------------
// SingletonPatternExample1.cs
//-------------------------------------------------------------------------------------
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//This real-world code demonstrates the Singleton pattern as a LoadBalancing object. Only a single instance (the singleton) of the class can be created
//because servers may dynamically come on- or off-line and every request must go throught the one object that has knowledge about the state of the (web) farm.
namespace SingletonPatternExample1
{
public class SingletonPatternExample1 : MonoBehaviour
{
void Start()
{
var balancer = LoadBalancer.Instance;
for (int i = 0; i < 15; i++)
{
string server = balancer.Server;
Debug.Log("Dispatch Request to: " + server);
}
}
}
public sealed class LoadBalancer
{
private static readonly object _syncLock = new object();
private static LoadBalancer _instance;
private readonly List<string> _servers = new List<string> { "ServerI", "ServerII", "ServerIII", "ServerIV", "ServerV" };
private readonly System.Random _random = new System.Random();
private LoadBalancer() { }
public static LoadBalancer Instance
{
get
{
if (_instance == null)
{
lock (_syncLock)
{
if (_instance == null)
{
_instance = new LoadBalancer();
}
}
}
return _instance;
}
}
public string Server
{
get
{
int r = _random.Next(_servers.Count);
return _servers[r];
}
}
}
}