Singleton Design Pattern.pptx - Singleton Pattern Singleton...

This preview shows page 1 - 8 out of 14 pages.

Singleton Pattern
Singleton Pattern Creational pattern limits a class to a single instantiation. Used when exactly one object is required to coordinate actions across an entire application.
UML
Deceptively Easy to Implement – C# sealed class BasicSingletonDemo { private static BasicSingletonDemo _demo = new BasicSingletonDemo(); private BasicSingletonDemo() { //private constructor - no one //can instantiate this class except //itself } public static BasicSingletonDemo GetInstance() { return _demo; } } void Main() { BasicSingletonDemo basic = BasicSingletonDemo.GetInstance(); }
Deceptively Easy to Implement - Java public class Main { public static void main (String[] args) { BasicSingletonDemo basic = BasicSingletonDemo. getInstance () ; } } final class BasicSingletonDemo { private static BasicSingletonDemo _demo = new BasicSingletonDemo() ; private BasicSingletonDemo () { //private constructor - no one //can instantiate this class except //itself } public static BasicSingletonDemo getInstance () { return _demo ; } }
Requirements 1. Default constructor must be private. 2. Instance is held in a private, static variable. 3. A static method or property (if C#) provides access to the static instance. 4. Must be sealed (C#) or final (Java).
Why is a Singleton Sealed / Final? Marking a class sealed or final prevents it from being subclassed. This ensures that your singleton remains a singleton. void Main() { UnsealedSingletonDemo unsealed = UnsealedSingletonDemo.GetInstance(); UnsealedSingletonDemo unsealedWorkaround = UnsealedSingletonDemo.AwfulWorkaround.GetInstance(); Console.WriteLine(unsealed.GetHashCode() + " -- " + unsealedWorkaround.GetHashCode()); } class UnsealedSingletonDemo { private static UnsealedSingletonDemo _demo = new

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture