What is the reasoning behind Singleton accessor names?
Over the course of a few projects, I have written a decent amount of class factory methods for accessing a Singleton instance of a class. I have always used some variation on the + (id)sharedSomething;
naming convention.
Apple, on the other hand, has a variety of naming conventions. For example:
// NSNotificationCenter
+ (id)defaultCenter;
// NSUserDefaults
+ (NSUserDefaults *)standardUserDefaults;
// UIApplication
+ (UIApplication *)sharedApplication;
Is there any rhyme or reason to the adjective placed before the noun in those names that I should be aware of when naming my own methods? I originally thought it might have something to do with "flexible" vs "strict" singleton designs, but NSFileManager and NSNotificationCenter both follow the +开发者_开发知识库 (id)defaultSomething convention, yet NSFileManager supports the allocation of other instances while NSNotificationCenter does not. I'm stumped.
EDIT: I was wrong in thinking NSNotificationCenter does not support the instantiation of new centers. It's just not terribly common, so the original hypothesis is not necessarily invalidated.
In general, the shared…
methods are for true singletons (NSApplication, NSWorkspace, etc.) while default…
or standard…
denotes a class that can be usefully instantiated, but where most clients will be happy just working with a single global instance. But there isn't any public written standard, and it seems primarily to have been a decision made whenever such a class was written.
I found, by complete happenstance, this position on the topic from the book iPhone App Development by Craig Hockenberry:
Unfortunately, there's no one standard for naming singletons. Older classes, such as those in the foundation, use the default prefix on the method name. Newer classes tend to use shared as a prefix.
I'll cite it as an alternative to the answer posted by @Chuck. The summary seems to be that there is no real pattern, while Chuck points to a rough correlation between true singletons and objects that are just commonly used as singletons, and Mr. Hockenberry points to a rough correlation in age.
It has nothing to do with "flexible" vs "strict" singleton designs. NSNotificationCenter and NSUserDefaults are not even Singletons. Do you really think flexibleSingleNotificationCenter is a better name than defaultCenter? Is there any single way that it helps the user of the method to know how it is implemented?
NSDeteriministicFiniteStateMachineToggleButton anyone?
精彩评论