Javatpoint Logo
Javatpoint Logo

Singleton Design pattern in C#

Th? Singl?ton d?sign patt?rn is on? of th? cr?ational d?sign patt?rns in C#. Its primary purpose is to ?nsur? that a class has only on? instanc? whil? providing a global point of acc?ss to that instanc?. This pattern is useful when you want to control access to a shar?d r?sourc? or ?nsur? that a singl? obj?ct coordinat?s actions within an application.

Th? Singl?ton d?sign patt?rn in C# ?nsur?s a singl? instanc? of a class is cr?at?d and provid?s global acc?ss to it. Its tim? and spac? compl?xiti?s ar? typically constant (O(1)), making it ?ffici?nt for managing shar?d r?sourc?s, such as configuration data or databas? conn?ctions. Th? patt?rn ?nforc?s thr?ad-saf? cr?ation wh?n impl?m?nt?d with doubl?-ch?ck locking.

How?v?r, it simplifi?s acc?ss to a singl? instanc?, and d?v?lop?rs should us? it judiciously to avoid introducing global stat? and maintain a cl?ar s?paration of conc?rns within th?ir cod?bas?. Th? Singl?ton patt?rn r?mains a valuabl? tool for solving specific d?sign chall?ng?s that r?quir? c?ntraliz?d control and coordination.

Common Us? Cas?s for th? Singl?ton Patt?rn:

Databas? Conn?ction Pool: In applications that int?ract with databas?s, you might us? a Singl?ton to manag? a conn?ction pool, ?nsuring ?ffici?nt us? of conn?ctions.

Logging: A Singl?ton Logg?r class can ?nsur? that all log m?ssag?s ar? dir?ct?d to a singl? log fil? or d?stination.

Configuration Manag?m?nt: Wh?n you hav? configuration s?ttings that should b? consist?nt across th? application, a Singl?ton can stor? and provid? acc?ss to th?s? s?ttings.

Caching: Managing a cach? of fr?qu?ntly us?d data can b?n?fit from a Singl?ton patt?rn to maintain a singl? cach? instanc?.

Structure of Singleton Design Pattern:

Th?re are several k?y points in the structure of th? Singl?ton Patt?rn in C#. Some main components of the Singleton Design Pattern are as follows:

Privat? Constructor: Th? class has a privat? constructor to pr?v?nt dir?ct instantiation from ?xt?rnal cod?.

Privat? Static Instanc? Variabl?: It contains th? singl? instanc? of th? class and is usually mark?d as static to ?nsur? shar?d acc?ss.

Static M?thod for Instanc? Acc?ss: A public static m?thod is provid?d to acc?ss th? singl? instanc?. This m?thod ?nsur?s that th? instanc? is cr?at?d if it doesn't ?xist or r?turns th? ?xisting instanc?.

Characteristics of Singleton Design Pattern:

Th? Singl?ton d?sign patt?rn has s?v?ral k?y characteristics that d?fin? its behaviour and purpos?. Und?rstanding th?s? characteristics is ?ss?ntial for ?ff?ctiv?ly impl?m?nting and using th? Singl?ton patt?rn in your softwar? d?sign.

Singl? Instanc?: Th? most fundam?ntal characteristic of th? Singl?ton patt?rn is that it ?nsur?s th?r? is only on? instanc? of th? class throughout th? lif?tim? of th? application. It m?ans that no matt?r how many tim?s you r?qu?st an instanc? of th? Singl?ton, you always g?t th? sam?, singl? instanc?.

Global Acc?ss: Th? Singl?ton provid?s a global point of acc?ss to its singl? instanc?. It means that any part of th? cod? can acc?ss th? Singl?ton instanc? without n??ding to pass r?f?r?nc?s to it. This global acc?ss simplifi?s th? proc?ss of int?racting with th? Singl?ton obj?ct.

Privat? Constructor: A Singl?ton class typically has a privat? constructor to ?nforc? th? singl? instanc? rul?. It pr?v?nts ?xt?rnal cod? from cr?ating additional instanc?s of th? class using th? n?w k?yword. Th? privat? constructor is on? of th? k?y f?atur?s that distinguish?s a Singl?ton from a r?gular class.

Lazy Initialization: In many impl?m?ntations, th? Singl?ton instanc? is cr?at?d only when it is first r?qu?st?d. It is known as lazy initialization. Lazy initialization can improv? p?rformanc? b?caus? th? Singl?ton is not cr?at?d until it's n??d?d. It h?lps cons?rv? r?sourc?s wh?n th? Singl?ton is not us?d during th? application's lif?cycl?.

Static Instanc? Variabl?: The Singl?ton class typically contains a private static variabl? that holds th? singl? instanc?. This variabl? ?nsur?s that th? instanc? is shar?d among all cod? that acc?ss?s it. It's oft?n nam?d "instanc?" or similar.


Let's take an example to demonstrate the Singleton Design Pattern in C#:


Both r?f?r?nc?s point to th? sam? Singl?ton instanc?.
Data from Singl?ton: Initial data
Modifi?d data from Singl?ton: N?w data


Using Syst?m: It is an import stat?m?nt, allowing you to us? typ?s and m?thods from th? Syst?m nam?spac?.

Public s?al?d class Singl?ton: It is th? d?claration of th? Singl?ton class. It is d?clar?d as s?al?d to pr?v?nt inh?ritanc?, ?nsuring that no d?riv?d class?s can b? cr?at?d.

privat? static volatil? Singl?ton instanc?: It is a privat? static variabl? instanc? us?d to hold th? singl? instanc? of th? Singl?ton class. It's mark?d as volatil? to ?nsur? that chang?s mad? by on? thr?ad ar? imm?diat?ly visibl? to oth?r thr?ads.

privat? static obj?ct syncRoot = n?w Obj?ct();: It is an obj?ct us?d for locking purpos?s to ?nsur? thr?ad saf?ty wh?n cr?ating th? Singl?ton instanc?.

privat? Singl?ton(): Th? privat? constructor ?nsur?s that no ?xt?rnal cod? can cr?at? instanc?s of th? Singl?ton class using th? n?w k?yword. It ?nforc?s th? singl?-instanc? rul?.

Public static Singl?ton G?tInstanc?(): It is a public static m?thod that provid?s acc?ss to th? Singl?ton instanc?. Insid? th? m?thod, it ch?cks wh?th?r th? instanc? is null. If it's null, it ?nt?rs a lock block to ?nsur? that only on? thr?ad at a tim? cr?at?s th? instanc?. It is known as doubl?-ch?ck locking. If th? instanc? is still null within th? lock, it cr?at?s th? Singl?ton instanc?. This patt?rn ?nsur?s that only on? instanc? is cr?at?d ?v?n in a multi-thr?ad?d ?nvironm?nt.

Public string G?tData(): This m?thod allows you to r?tri?v? th? som?Data fi?ld of th? Singl?ton instanc?.

Public void S?tData(string data): This m?thod allows you to modify th? som?Data fi?ld of th? Singl?ton instanc?.

This Program class d?monstrat?s th? usag? of th? Singl?ton patt?rn:

  • It obtains two r?f?r?nc?s (singl?ton1 and singl?ton2) to th? Singl?ton instanc? using Singl?ton.G?tInstanc?().
  • It ch?cks if both r?f?r?nc?s point to th? sam? Singl?ton instanc?. If th?y do, it prints a m?ssag? confirming th? Singl?ton patt?rn is working as ?xp?ct?d.
  • It us?s th? Singl?ton instanc? to r?tri?v? and modify th? data using th? G?tData() and S?tData() m?thods.

When you run this program, you should s?? th? output as shown.

Compl?xity Analysis:

Tim? Compl?xity:

Th? tim? compl?xity of th? Singl?ton patt?rn impl?m?ntation is g?n?rally O(1), which signifi?s constant tim? compl?xity. It applies to k?y op?rations:

Cr?ation of Singl?ton Instanc? (G?tInstanc?() m?thod): Cr?ating th? Singl?ton instanc? is a constant-tim? op?ration b?caus? it occurs only onc? throughout th? application's ?x?cution, r?gardl?ss of how many tim?s G?tInstanc?() is invok?d. Th? logic insid? G?tInstanc?() involv?s a simpl? null ch?ck, and in som? cas?s, a lock for thr?ad saf?ty. Th?s? op?rations do not d?p?nd on th? siz? of th? data or th? fr?qu?ncy of m?thod calls.

Acc?ssing Data (G?tData() and S?tData() m?thods): Acc?ssing or modifying data within th? Singl?ton instanc? is also typically O(1). Th?s? m?thods dir?ctly acc?ss a class fi?ld (som?Data), which doesn't vary in ?x?cution tim? bas?d on th? input siz? or th? numb?r of m?thod calls.

Locking M?chanism: Th? us? of th? lock stat?m?nt in th? G?tInstanc?() m?thod introduc?s synchronization to ?nsur? thr?ad saf?ty. Locking and r?l?asing th? lock ar? consid?r?d O(1). Although, in highly concurr?nt sc?narios, th? tim? compl?xity might b? aff?ct?d by thr?ad cont?ntion. On av?rag?, th? compl?xity r?mains constant.

Spac? Compl?xity:

The spac? compl?xity of th? Singl?ton patt?rn impl?m?ntation is also O(1), indicating constant spac? usag?. K?y compon?nts includ?:

Singl?ton Instanc? (instanc?): Storing th? Singl?ton instanc? r?quir?s constant spac?. No matter how many times GetInstance() is called, there is only ever one instance, and the memory footprint remains fixed.

Additional Data M?mb?rs (?.g., som?Data): Th? spac? compl?xity for additional data m?mb?rs within th? Singl?ton class d?p?nds on th?ir charact?ristics. In th? provid?d cod?, som?Data is a string and its spac? compl?xity d?p?nds on th? l?ngth of th? string. G?n?rally, class fi?lds hav? a spac? compl?xity of O(1) unl?ss th?y involv? variabl?-siz?d coll?ctions or arrays.

Locking M?chanism (?.g., syncRoot): Th? spac? compl?xity for th? syncRoot obj?ct us?d for locking is constant as w?ll. It's a r?f?r?nc? to a fix?d-siz? obj?ct, and its m?mory usag? doesn't change with input.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA