Singleton pattern In software engineering , the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system . The term comes from the mathematical concept of a singleton . Critics consider the singleton to be an anti-pattern in that it is frequently used in scenarios where it is not beneficial, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application.Overview The singletondesign pattern is one of the twenty-three well-known "Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. The singleton design pattern solves problems like: How can it be ensured that a class has only one instance? How can the sole instance of a class be accessed easily? How can a class control its instantiation? How can the number of instances of a class be restricted? The singleton design pattern describes how to solve such problems: Hide the constructor of the class. Define a public static operation that returns the sole instance of the class. The key idea in this pattern is to make the class itself responsible for controlling its instantiation. The hidden constructor ensures that the class can never be instantiated from outside the class.The public static operation can be accessed easily by using the class name and operation name.Common uses The abstract factory , factory method , builder , and prototype patterns can use singletons in their implementation. Facade objects are often singletons because only one facade object is required. State objects are often singletons. Singletons are often preferred to global variables because: * They do not pollute the global namespace with unnecessary variables. * They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources. An implementation of the singleton pattern must: ensure that only one instance of the singleton class ever exists; and provide global access to that instance. Typically, this is done by: The instance is usually stored as a private static variable ; the instance is created when the variable is initialized, at some point before the static method is first called. The following is a sample implementation written in Java . public final class Singleton C# implementation public sealed class Singleton In C# you can also use static classes to create singletons, where the class itself is the singleton. public static class Singleton Lazy initialization A singleton implementation may use lazy initialization , where the instance is created when the static method is first invoked. If the static method might be called from multiple threads simultaneously, measures may need to be taken to prevent race conditions that could result in the creation of multiple instances of the class. The following is a thread-safe sample implementation, using lazy initialization with double-checked locking , written in Java. public final class Singleton Dart implementation class Singleton PHP implementation class Singleton Java Implementation public class Coin Kotlin Implementation Kotlin object keyword declares a singleton class object Coin GetInstance is thread safe implementation of Singleton. unit SingletonPattern; interface type TTest = class sealed strict private FCreationTime: TDateTime; public constructor Create; property CreationTime: TDateTime read FCreationTime; end; function GetInstance: TTest; implementation uses SysUtils , SyncObjs ; var FCriticalSection: TCriticalSection; FInstance: TTest; function GetInstance: TTest; begin FCriticalSection.Acquire; try if not Assigned then FInstance := TTest.Create; Result := FInstance; finally FCriticalSection.Release; end; end; constructor TTest.Create; begin inherited Create; FCreationTime := Now; end; initialization FCriticalSection := TCriticalSection.Create; finalization FreeAndNil; end. Usage: procedure TForm3.btnCreateInstanceClick; var i: integer; begin for i := 0 to 5 do ShowMessage; end;
Popular articles Javier Milei - Argentine libertarian economist, author, radio conductor and public speaker sympathetic to the Austrian School of economic thought. He became widely known for his regular ...Jimmy Carter - American politician, philanthropist, and former farmer who served as the 39th president of the United States from 1977 to 1981. A member of the Democratic Party, he previ...UEFA Euro 2024 - The 2024 UEFA European Football Championship , commonly referred to as UEFA Euro 2024 or simply Euro 2024 , will be the 17th edition of the UEFA European Championship, the quadrennial internationa...Argentina - country located mostly in the southern half of South America. Sharing the bulk of the Southern Cone with Chile to the west, the country is also b...Sam Altman - American entrepreneur, investor, programmer, and blogger. He is the former president of Y Combinator and now the CEO of OpenAI. Early life and education. ...Rosalynn Carter - American who served as First Lady of the United States from 1977 to 1981 as the wife of President Jimmy Carter. For decades, she has been a leading advocate for numerou...Next Argentine presidential election - Next Argentine presidential election - presidential election in Argentina....Popular movies The Hunger Games (film) - 2012 American dystopian action thriller science fiction-adventure film directed by Gary Ross and based on Suzanne Collins’s 2008 novel of the same name. It is the first insta...untitled Captain Marvel sequel - part of Marvel Cinematic Universe....Killers of the Flower Moon (film project) - Killers of the Flower Moon - film project in United States of America. It was presented as drama, detective fiction, thriller. The film project starred Leonardo Dicaprio, Robert De Niro. Director of...Five Nights at Freddy's (film) - Five Nights at Freddy's - film published in 2017 in United States of America. Scenarist of the film - Scott Cawthon....Popular video games Minecraft - sandbox video game developed by Mojang Studios. Created by Markus "Notch" Persson in the Java programming language and released as a public alpha for personal computers in 2...Grand Theft Auto V - 2013 action-adventure game developed by Rockstar North and published by Rockstar Games. It is the first main entry in the Grand Theft Auto series since 2008's Grand Theft ...Roblox - online game platform and game creation system that allows users to program games and play games created by other users. Founded by David Baszucki and Erik Cassel in 2004 and released in...Baldur's Gate III - upcoming role-playing video game developed and published by Larian Studios for Microsoft Windows and the Stadia streaming service. It is the third main game in the Baldur's ...Alan Wake - action-adventure video game developed by Remedy Entertainment and published by Microsoft Studios, released for the Xbox 360 and Microsoft Windows. The story follows best-selling thri...Fortnite - online video game developed by Epic Games and released in 2017. It is available in three distinct game mode versions that otherwise share the same general gameplay and game engine: ...Super Mario RPG - is a role-playing video game developed by Square and published by Nintendo for the Super Nintendo Entertainment System in 1996. It was directed by Yoshihiko Maekawa and Chihiro Fujioka and produced by...Popular books Book of Revelation - The Book of Revelation is the final book of the New Testament, and consequently is also the final book of the Christian Bible. Its title is derived from the first word of the Koine Greek text: apok...Book of Genesis - account of the creation of the world, the early history of humanity, Israel's ancestors and the origins...Gospel of Matthew - The Gospel According to Matthew is the first book of the New Testament and one of the three synoptic gospels. It tells how Israel's Messiah, rejected and executed in Israel, pronounces judgement on ...Michelin Guide - Michelin Guides are a series of guide books published by the French tyre company Michelin for more than a century. The term normally refers to the annually published Michelin Red Guide , the oldest...Psalms - The Book of Psalms , commonly referred to simply as Psalms , the Psalter or "the Psalms", is the first book of the Ketuvim , the third section of the Hebrew Bible, and thus a book of th...Ecclesiastes - Ecclesiastes is one of 24 books of the Tanakh , where it is classified as one of the Ketuvim . Originally written c. 450–200 BCE, it is also among the canonical Wisdom literature of the Old Tes...The 48 Laws of Power - non-fiction book by American author Robert Greene. The book...Popular television series The Crown (TV series) - historical drama web television series about the reign of Queen Elizabeth II, created and principally written by Peter Morgan, and produced by Left Bank Pictures and Sony Pictures Tel...Friends - American sitcom television series, created by David Crane and Marta Kauffman, which aired on NBC from September 22, 1994, to May 6, 2004, lasting ten seasons. With an ensemble cast sta...Young Sheldon - spin-off prequel to The Big Bang Theory and begins with the character Sheldon...Modern Family - American television mockumentary family sitcom created by Christopher Lloyd and Steven Levitan for the American Broadcasting Company. It ran for eleven seasons, from September 23...Loki (TV series) - upcoming American web television miniseries created for Disney+ by Michael Waldron, based on the Marvel Comics character of the same name. It is set in the Marvel Cinematic Universe, shar...Game of Thrones - American fantasy drama television series created by David Benioff and D. B. Weiss for HBO. It...Shameless (American TV series) - American comedy-drama television series developed by John Wells which debuted on Showtime on January 9, 2011. It...
OWIKI.org . Text is available under the Creative Commons Attribution-ShareAlike License.