-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask3_Singleton.cs
More file actions
86 lines (76 loc) · 2.17 KB
/
Copy pathTask3_Singleton.cs
File metadata and controls
86 lines (76 loc) · 2.17 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
80
81
82
83
84
85
86
namespace Lab2;
public sealed class Authenticator
{
private static Authenticator? _instance;
private static readonly object _lock = new object();
private List<string> _users = new List<string>();
private Authenticator()
{
Console.WriteLine(" Authenticator створено");
}
public static Authenticator Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
_instance = new Authenticator();
}
}
return _instance;
}
}
public void Login(string username, string password)
{
if (password == "1234")
{
_users.Add(username);
Console.WriteLine($" {username} увійшов успішно");
}
else
{
Console.WriteLine($" {username} - невірний пароль");
}
}
public void Logout(string username)
{
_users.Remove(username);
Console.WriteLine($" {username} вийшов");
}
public void ShowUsers()
{
Console.WriteLine($" Онлайн: {string.Join(", ", _users)}");
}
}
public static class Task3Demo
{
public static void Run()
{
Console.WriteLine("\nЗавдання 3: Singleton");
var a1 = Authenticator.Instance;
var a2 = Authenticator.Instance;
Console.WriteLine($"\n a1 == a2: {ReferenceEquals(a1, a2)}");
a1.Login("Іван", "1234");
a2.Login("Марія", "1234");
a1.Login("Хакер", "wrongpass");
a1.ShowUsers();
a2.Logout("Іван");
a1.ShowUsers();
Console.WriteLine("\n Тест потоків:");
var threads = new List<Thread>();
for (int i = 0; i < 4; i++)
{
int n = i;
threads.Add(new Thread(() =>
{
var inst = Authenticator.Instance;
Console.WriteLine($" Thread {n}: hash={inst.GetHashCode()}");
}));
}
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());
}
}