Skip to content

Commit 404189c

Browse files
committed
Singleton: improve conceptual example
1 parent c4969e3 commit 404189c

File tree

1 file changed

+46
-22
lines changed

1 file changed

+46
-22
lines changed

Singleton.Conceptual/Program.cs

Lines changed: 46 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,56 @@
1-
using System;
1+
// EN: Singleton Design Pattern
2+
//
3+
// Intent: Ensure that a class has a single instance, and provide a global point
4+
// of access to it.
5+
//
6+
// RU: Паттерн Одиночка
7+
//
8+
// Назначение: Гарантирует существование единственного экземпляра класса и
9+
// предоставляет глобальную точку доступа к нему.
10+
11+
using System;
212

313
namespace Singleton
414
{
5-
class Program
15+
// EN: The Singleton class defines the `getInstance` method that lets clients
16+
// access the unique singleton instance.
17+
//
18+
// RU: Класс Одиночка предоставляет метод getInstance, который позволяет
19+
// клиентам получить доступ к уникальному экземпляру одиночки.
20+
class Singleton
621
{
7-
static void Main(string[] args)
22+
private static Singleton _instance;
23+
24+
private static object _lock = new object();
25+
26+
private Singleton()
27+
{ }
28+
29+
// EN: The static method that controls the access to the singleton instance.
30+
//
31+
// This implementation let you subclass the Singleton class while keeping
32+
// just one instance of each subclass around.
33+
//
34+
// RU: Статический метод, управляющий доступом к экземпляру одиночки.
35+
//
36+
// Эта реализация позволяет вам расширять класс Одиночки,
37+
// сохраняя повсюду только один экземпляр каждого подкласса.
38+
public static Singleton getInstance()
839
{
9-
Client client = new Client();
10-
client.ClientCode();
40+
lock (_lock)
41+
{
42+
return _instance ?? (_instance = new Singleton());
43+
}
1144
}
1245
}
13-
46+
1447
class Client
1548
{
1649
public void ClientCode()
1750
{
51+
// EN: The client code.
52+
//
53+
// RU: Клиентский код.
1854
Singleton s1 = Singleton.getInstance();
1955
Singleton s2 = Singleton.getInstance();
2056

@@ -29,24 +65,12 @@ public void ClientCode()
2965
}
3066
}
3167

32-
class Singleton
68+
class Program
3369
{
34-
private static Singleton instance;
35-
36-
private static object obj = new object();
37-
38-
private Singleton()
39-
{ }
40-
41-
public static Singleton getInstance()
70+
static void Main(string[] args)
4271
{
43-
lock(obj)
44-
{
45-
if (instance == null)
46-
instance = new Singleton();
47-
}
48-
49-
return instance;
72+
Client client = new Client();
73+
client.ClientCode();
5074
}
5175
}
5276
}

0 commit comments

Comments
 (0)