日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

IOS开发基础之单例模式

發(fā)布時(shí)間:2023/12/18 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 IOS开发基础之单例模式 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

IOS開(kāi)發(fā)基礎(chǔ)之單例模式


各種編程語(yǔ)言都有單例模式。起初23設(shè)計(jì)模式是來(lái)自C++總結(jié)設(shè)計(jì)出來(lái)的。其他編程語(yǔ)言陸續(xù)也出來(lái)了。
直接上源碼。為了方便起見(jiàn),打印日志我也放到源碼里面了。

// // ViewController.m // 22-單例模式 // // Created by 魯軍 on 2021/2/17. //#import "ViewController.h" #import "NetworkTools.h" @interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.NetworkTools *t12 = [NetworkTools sharedNetworkTools];NetworkTools *t1 = [NetworkTools sharedNetworkToolsOnce];NetworkTools *t2 = [NetworkTools sharedNetworkToolsOnce];NSLog(@"%@",t1);NSLog(@"%@",t2);//打印地址//2021-02-17 23:06:32.364581+0800 22-單例模式[3109:136705] <NetworkTools: 0x600003568140> // 2021-02-17 23:06:32.365020+0800 22-單例模式[3109:136705] <NetworkTools: 0x600003568140>[self testBeginAndEndTimeSynchronized];[self testBeginAndEndTimeOne]; // 2021-02-17 23:11:33.338995+0800 22-單例模式[3237:141283] 加鎖 0.001164 // 2021-02-17 23:11:33.339635+0800 22-單例模式[3237:141283] One 0.000389}//測(cè)試加鎖的 創(chuàng)建時(shí)間 -(void)testBeginAndEndTimeSynchronized{CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();for(int i=0;i<10000;i++){[NetworkTools sharedNetworkTools];}CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();NSLog(@"加鎖 %lf",end-start);}//測(cè)試Once的時(shí)間 -(void)testBeginAndEndTimeOne{CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();for(int i=0;i<10000;i++){[NetworkTools sharedNetworkToolsOnce];}CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();NSLog(@"One %lf",end-start); } @end // // NetworkTools.h // 22-單例模式 // // Created by 魯軍 on 2021/2/17. //#import <Foundation/Foundation.h>NS_ASSUME_NONNULL_BEGIN@interface NetworkTools : NSObject+(instancetype)sharedNetworkTools;+(instancetype)sharedNetworkToolsOnce;@endNS_ASSUME_NONNULL_END // // NetworkTools.m // 22-單例模式 // // Created by 魯軍 on 2021/2/17. //#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;//dispatch_once 線程安全的 性能高static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{if(instance==nil){instance = [[self alloc] init];}});return instance; }@end

總結(jié)

以上是生活随笔為你收集整理的IOS开发基础之单例模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。