解析Cocoa單態(tài) singleton設計模式
作者:佚名
本文介紹的是解析Cocoa單態(tài) singleton設計模式,主要是以代碼來實現(xiàn)實例操作,我們先來看內(nèi)容。
解析Cocoa單態(tài) singleton設計模式是本文要介紹的內(nèi)容,不多說,先來看內(nèi)容,如果你準備寫一個類,希望保證只有一個實例存在,同時可以得到這個特定實例提供服務的入口,那么可以使用單態(tài)設計模式。單態(tài)模式在Java、C++中很常用,在Cocoa里,也可以實現(xiàn)。
由于自己設計單態(tài)模式存在一定風險,主要是考慮到可能在多線程情況下會出現(xiàn)的問題,因此蘋果官方建議使用以下方式來實現(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設計模式的內(nèi)容介紹完了,希望本文對你有所幫助!
責任編輯:zhaolei
來源:
Cocoa China