On design patterns: When should I use the singleton?

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

    I use it for an object encapsulating command-line parameters when dealing with pluggable modules. The main program doesn't know what the command-line parameters are for modules that get loaded (and doesn't always even know what modules are being loaded). e.g., main loads A, which doesn't need any parameters itself (so why it should take an extra pointer / reference / whatever, I'm not sure - looks like pollution), then loads modules X, Y, and Z. Two of these, say X and Z, need (or accept) parameters, so they call back to the command-line singleton to tell it what parameters to accept, and the at runtime they call back to find out if the user actually has specified any of them.

    In many ways, a singleton for handling CGI parameters would work similarly if you're only using one process per query (other mod_* methods don't do this, so it'd be bad there - thus the argument that says you shouldn't use singletons in the mod_cgi world in case you port to the mod_perl or whatever world).

提交回复
热议问题