On design patterns: When should I use the singleton?

后端 未结 20 3538
失恋的感觉
失恋的感觉 2020-11-22 02:45

The glorified global variable - becomes a gloried global class. Some say breaking object-oriented design.

Give me scenarios, other than the good old logger where it

20条回答
  •  天命终不由人
    2020-11-22 03:40

    You use the Singleton design pattern when you want to ensure that a class will have one instance, and that instance will have a global point of access to it.

    So let's say that you have an application that requires to a database to process CRUD operations. Ideally you'd use the same connection object to the database to access the database and perform the CRUD operations.

    Therefore, in order to ensure that the database class will have one object, and that same object will be used through out the application we implement the singleton design pattern.

    Ensure that your constructor is private and that you provide a static method to provide access to the single object of the singleton class

提交回复
热议问题