Singleton
Minimal coupling is a key guiding principle of Cocoa's design and the quality that most contributes to programmer productivity.
pp148
The Singleton pattern is used when there must be exactly one instance of a class, and it must be easily accessible to other objects in an application. Usually, the Cocoa documentation uses the term shared instance when the Singleton pattern is in use.
In Cocoa, one example of a Singleton is the NSApplication class. It maintains the application's connection to the window server for drawing and receiving events. Cocoa optionally takes advantage of Dynamic Creation and Bundles to substitute an instance of your own class for the default NSApplication instance.
Motivation
Define conventions for the creation of and access to an instance in cases where only one instance of a class should be created. Often singletons represent physical devices. At other times they represent virtual resouces or other system properties that are singular and can not or should not be duplicated. It is useful to have a one-to-one relationship between instances and the devices or concepts they represent.
Solution
Any class that uses the Singleton pattern must achieve three goals:
Encapsulate a shared resource.
Provide a standard way to create one shared instance.
Provide a standard way to access the one shared instance.
Encapsulating a Shared Resource pp150
Using a class to encapsulate a global variable is an ideal solution. Classes exist to encapsulate information about instances and provide a single interface for creating instances. Using an instance of MyGameHighScoreManager to manage scores and using the MyGameHighScoreManager class itself to encapsulate accessto the instanceis the cleanest way to achieve the goals of flexibility and maintainability.
Creating and Accessing a Shared Instance
A class method needs to be added to allow for access to the shared instance.
@interface MyGameHighScoreManager : NSObject
{
}
+ (id)sharedInstance;
- (void)registerScore:(NSNumber *)score
playerName:(NSString *)name;
- (NSEnumerator *)scoreEnumerator;
@end
A basic implementation of the +sharedInstance method might be like this:
+ (MyGameHighScoreManager *)sharedInstance
{
static MyGameHighScoreManager *myInstane = nil;
if(!myInstance)
{
myInstance = [[[self class] alloc] init];
//any other special initialiation as required here
}
return myInstance;
}
?p152
Contolling Instantiation
To fully implement the Singleton pattern, it is necessary to prevent the creation of multiple instances of a class.
实现没看懂pp154
Deallocation
Usually, a shared instance should be instantiated only once during the lifetime of an application and only be shut down when the application terminates.
In some case, deallocate and instantiate later...
+ (void)attemptDealloc
{
if([myInstance retainCount] != 1) return;
[myInstance release];
myInstance = nil;
}
+(BOOL)sharedInstanceExists
{
return (nil != myInstance);
}
//if there is multiple call on init
-(id)init
{
if(![[self calss] sharedInstanceExists])
{
//
}
return self;
}
Examples in Cocoa
There are several classes in Cocoa that are singletons.
NSApplication encapsulates the connection between a Cocoa application and window server. It receives events and distributes them to the correct objects viathe First Responder pattern. It alsosends drawing commands. Finaly, it represents the application itself, handling all application-level eventssuch as hiding and quitting. The global variable NSApp is a pointer to the shared NSApplication instance.
Another example is NSWorkspace, which encapsulatesthe application's communicationwith the Mac OS X Finder and underlying file systems.
The NSFontManager class is also a singleton. It represents the collection of all the fonts installed on the system and manages access to them so that all font objects can be shared.
NSDocumentController, NSHelpManager, NSNull, NSProcessInfo, NSScriptExecutionContxt, and NSUserDefaults.
look for "shared" in the class method names
Consequences
A shared object is used in cases where a particular class should be instantiated once and only once.
To implement this pattern, the class object provides a method that is globally accessible and canbe used to obtain the shared-object instance. At the same time, the +alloc method is disabled to prevent you from creating extra instances. The single, shared instance is created the first time you ask for it, and then the same instance is returned every time thereafter.
posted on 2013-02-25 01:26 Chansonyan 阅读(214) 评论(0) 收藏 举报
浙公网安备 33010602011771号