The Singleton Design Pattern

The Singleton Design Pattern

(Private Constructor) the way to prevents direct instantiation of the class from outside its own implementation.

  • Advantages of Singleton Single instance: The singleton guarantees that the class has only one instance throw the app.
  • Global Access: singleton is globally accessible, possible to access its method or properties from anywhere.
  • Lazy Installation: It supports lazy installation, meaning the instance is created only when it is accessed for the first time.
  • Disadvantage of Singleton Global state: Singleton provides a global state which can make it harder to track also changing singleton instances can affect other app parts, potentially resulting hidden bugs.
  • Tight Coupling: use of singleton lead to tight coupling between class which make difficult to modify or replace.
  • Test Challenges: unit testing is more challenging because we need to isolate and test dependent components.
  • Violates SRP: single responsibility principle states that every class has single task to do, her we have 2 one to create an instance the other to do the actual task.
  • Breaks the OCP: open closed principle (open for extension, close for modification) the singleton class always returns its own instance and never open for extension.
  • When Should we use Singleton Single Instance : we need to ensure that only one instance of class through the app.
  • Global Access: we want single point to access the instance. Limited Resource Usage: it’s limited expensive resources such as DB, file system
  • Real World EX Logger : it ensures that one instance of logger exists and all parts can access. DB connection: with connect to DB it’s a good way to have only one shared connection.

class Singleton {
  /// private constructor
  Singleton._();
  /// the one and only instance of this singleton
  static final instance = Singleton._();
}        

Resources

要查看或添加评论,请登录

Ali Radwan ????的更多文章

社区洞察

其他会员也浏览了