3 ms·
Globals like a and b are fields of the singleton, not instance of singleton(s). The global space is the singleton (or a juxtaposition of singletons, if we let a
by wott 6y ago
Globals like a and b are fields of the singleton, not instance of singleton(s). The global space is the singleton (or a juxtaposition of singletons, if we let aside the lack of visibility protection), and global variables and functions are the fields (members) and the methods of the singleton.
- AnimalMuppet 6y agoYou can look at it that way, I suppose, though I consider it to be a fairly odd perspective. But it doesn't help at all with the problem of enforcing that there be only one ThingThereCanBeOnlyOneOf. Therefore globals are not a true solution to the problem that singletons are trying to solve.
- bcrosby95 6y agoJust use static methods.
- candiodari 6y agoSingletons solve several problems with static methods, namely that you can't change their behavior (e.g. do error logging to both the global error log and a per-request log, then at other times do it to a log buffer for testing, and NOT to anywhere else). At least with a singleton you can create a bunch of "standard configurations" by calling them with a different constructor at startup time. So you can have a test DB during tests, different log targets, read from different filesystem (not the real one, but the one in the testdata/ directory) ... Better yet is to have a "context" abstraction that you pass down the chain. Issue with that is, every method needs to have a first parameter that is the context ... so it requires some discipline. Some frameworks (java @#$@#%@# servlet spec for example) make this parameter implicit and then use something akin to exception resolution to get this parameter (so when you do GetContext(), it unwinds the stack to give you the correct context). That makes things very complicated, and is an invisible LOT of state that gets passed down the stack. Still better than singletons or static methods, but good luck figuring out why a context is set to X. In all cases you need to be very careful to USE the context. DO NOT use database except the one in the context, no caches except the one in the context, no filesystem reading, logging, ... except by redirecting through the context.
- deleted 6y ago[deleted]