On design patterns: When should I use the singleton?

后端 未结 20 3342
失恋的感觉
失恋的感觉 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:24

    A Singleton candidate must satisfy three requirements:

    • controls concurrent access to a shared resource.
    • access to the resource will be requested from multiple, disparate parts of the system.
    • there can be only one object.

    If your proposed Singleton has only one or two of these requirements, a redesign is almost always the correct option.

    For example, a printer spooler is unlikely to be called from more than one place (the Print menu), so you can use mutexes to solve the concurrent access problem.

    A simple logger is the most obvious example of a possibly-valid Singleton, but this can change with more complex logging schemes.

提交回复
热议问题