解析Cocoa單態(tài) singleton設(shè)計模式
解析Cocoa單態(tài) singleton設(shè)計模式是本文要介紹的內(nèi)容,不多說,先來看內(nèi)容,如果你準(zhǔn)備寫一個類,希望保證只有一個實(shí)例存在,同時可以得到這個特定實(shí)例提供服務(wù)的入口,那么可以使用單態(tài)設(shè)計模式。單態(tài)模式在Java、C++中很常用,在Cocoa里,也可以實(shí)現(xiàn)。
由于自己設(shè)計單態(tài)模式存在一定風(fēng)險,主要是考慮到可能在多線程情況下會出現(xiàn)的問題,因此蘋果官方建議使用以下方式來實(shí)現(xiàn)單態(tài)模式:
- static MyGizmoClass *sharedGizmoManager = nil;
- (MyGizmoClass*)sharedManager
- {
- @synchronized(self) {
- if (sharedGizmoManager == nil) {
- [[self alloc] init]; // assignment not done here
- }
- }
- return sharedGizmoManager;
- }
- (id)allocWithZone:(NSZone *)zone
- {
- @synchronized(self) {
- if (sharedGizmoManager == nil) {
- sharedGizmoManager = [super allocWithZone:zone];
- return sharedGizmoManager; // assignment and return on first allocation
- }
- }
- return nil; //on subsequent allocation attempts return nil
- }
- (id)copyWithZone:(NSZone *)zone
- {
- return self;
- }
- (id)retain
- {
- return self;
- }
- (unsigned)retainCount
- {
- return UINT_MAX; //denotes an object that cannot be released
- }
- (void)release
- {
- //do nothing
- }
- (id)autorelease
- {
- return self;
小結(jié):解析Cocoa單態(tài) singleton設(shè)計模式的內(nèi)容介紹完了,希望本文對你有所幫助!