-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathChocolateBoiler_ThreadSafe.cs
More file actions
79 lines (71 loc) · 2.37 KB
/
ChocolateBoiler_ThreadSafe.cs
File metadata and controls
79 lines (71 loc) · 2.37 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreationalPatterns.Singleton
{
public sealed class ChocolateBuilder_ThreadSafe
{
public bool Empty { get; set; }
public bool Boiled { get; set; }
// singleton instance
// the volatile keyword ensures that multiple threads handle the singleton instance variable correctly
private static volatile ChocolateBuilder_ThreadSafe instance;
private static object syncLock = new object();
private ChocolateBuilder_ThreadSafe()
{
this.Empty = true;
this.Boiled = false;
}
public static ChocolateBuilder_ThreadSafe Instance
{
get
{
// Check for an instance and if there isn't one, enter a locked block
if (instance == null)
{
lock (syncLock)
{
// Once in the block, check again and if still null
if(instance == null)
{
instance = new ChocolateBuilder_ThreadSafe();
}
}
}
return instance;
}
}
public void Fill()
{
// To fill the boiler, it must be empty, and once it's full, we set the empty and boiled flags
if (this.Empty)
{
this.Empty = false;
this.Boiled = false;
// fill the boiler with a milk/chocolate mixture
}
}
public void Drain()
{
// To drain the boiler, it must be full and also boiled.
// Once it is drained we set the Empty property back to true
if (!this.Empty && this.Boiled)
{
// drain the boiled milk and chocolate
this.Empty = true;
}
}
public void Boil()
{
// To boil the mixture, the boiler has to be full and not already boiled.
// Once it is boiled we set the boiled flag to true
if (!this.Empty && !this.Boiled)
{
// bring the contents to a boil
this.Boiled = true;
}
}
}
}