forked from TastSong/GameProgrammerStudyNotes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingletonPattern.cs
More file actions
49 lines (41 loc) · 1.05 KB
/
SingletonPattern.cs
File metadata and controls
49 lines (41 loc) · 1.05 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
//-------------------------------------------------------------------------------------
// SingletonStructure.cs
//-------------------------------------------------------------------------------------
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SingletonPattern : MonoBehaviour
{
void Start()
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
// Test for same instance
if (s1 == s2)
{
Debug.Log("Objects are the same instance");
}
}
}
/// <summary>
/// The 'Singleton' class
/// </summary>
class Singleton
{
private static Singleton _instance;
// Constructor is 'protected'
protected Singleton()
{
}
public static Singleton Instance()
{
// Uses lazy initialization.
// Note: this is not thread safe.
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}