生活随笔
收集整理的這篇文章主要介紹了
IOS开发基础之单例模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
IOS開發基礎之單例模式
各種編程語言都有單例模式。起初23設計模式是來自C++總結設計出來的。其他編程語言陸續也出來了。
直接上源碼。為了方便起見,打印日志我也放到源碼里面了。
#import "ViewController.h"
#import "NetworkTools.h"
@interface ViewController
()@end@implementation ViewController
- (void)viewDidLoad
{[super viewDidLoad
];NetworkTools
*t12
= [NetworkTools sharedNetworkTools
];NetworkTools
*t1
= [NetworkTools sharedNetworkToolsOnce
];NetworkTools
*t2
= [NetworkTools sharedNetworkToolsOnce
];NSLog(@"%@",t1
);NSLog(@"%@",t2
);
[self testBeginAndEndTimeSynchronized
];[self testBeginAndEndTimeOne
];
}
-(void)testBeginAndEndTimeSynchronized
{CFAbsoluteTime start
= CFAbsoluteTimeGetCurrent();for(int i
=0;i
<10000;i
++){[NetworkTools sharedNetworkTools
];}CFAbsoluteTime end
= CFAbsoluteTimeGetCurrent();NSLog(@"加鎖 %lf",end
-start
);}
-(void)testBeginAndEndTimeOne
{CFAbsoluteTime start
= CFAbsoluteTimeGetCurrent();for(int i
=0;i
<10000;i
++){[NetworkTools sharedNetworkToolsOnce
];}CFAbsoluteTime end
= CFAbsoluteTimeGetCurrent();NSLog(@"One %lf",end
-start
);
}
@end
#import <Foundation/Foundation.h>NS_ASSUME_NONNULL_BEGIN
@interface NetworkTools
: NSObject
+(instancetype
)sharedNetworkTools
;+(instancetype
)sharedNetworkToolsOnce
;@endNS_ASSUME_NONNULL_END
#import "NetworkTools.h"@implementation NetworkTools
+(instancetype
)sharedNetworkTools
{static id instance
= nil
;@synchronized
(self) {if(instance
==nil
){instance
= [[self alloc
] init
];}}return instance
;}+(instancetype
)sharedNetworkToolsOnce
{static id instance
= nil
;static dispatch_once_t onceToken
;dispatch_once(&onceToken
, ^{if(instance
==nil
){instance
= [[self alloc
] init
];}});return instance
;
}@end
總結
以上是生活随笔為你收集整理的IOS开发基础之单例模式的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。