两种创建单例的方法
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
?? 1.
單例模式是在實際項目開發(fā)中用到比較多的一種設(shè)計模式,設(shè)計原理是整個系統(tǒng)只產(chǎn)生一個對象實例,通過一個統(tǒng)一的方法對外提供這個實例給外部使用。
在Java中,構(gòu)造單例一般將類的構(gòu)造函數(shù)聲明為private類型,然后通過一個靜態(tài)方法對外提供實例對象,那么,在OC中,如何實現(xiàn)單例的,請看下面完整代碼。
@implementation Car
//聲明一個靜態(tài)對象引用并賦為nil
static Car *sharedInstance= nil;
//聲明類方法(+為類方法,也就是Java中的靜態(tài)方法)
+(Car *) sharedInstance
{
? ? ?if(!sharedInstance)
? ? ?{
? ? ? ? ??sharedInstance = [[self alloc] init];
? ? ?}
? ? ?return?sharedInstance;
}
@end
//覆蓋allocWithZone:方法可以防止任何類創(chuàng)建第二個實例。使用synchronized()可以防止多個線程同時執(zhí)行該段代碼(線程鎖)
+(id)allocWithZone:(NSZone *) zone
{
? ? ?@synchronized(self)
? ? ?{
? ? ? ? ? if(sharedInstance == nil)
? ? ? ? ? {
? ? ? ? ? ? ? ?sharedInstance = [super allocWithZone:zone];
? ? ? ? ? ? ? ?return?sharedInstance;
? ? ? ? ? }
? ? ?}
? ? ?return?sharedInstance;
}
好了,到這里,OC中的單例就創(chuàng)建完成了,使用的話,直接類名調(diào)用類方法即可
?? 2.在開發(fā)中我們會用到NSNotificationCenter、NSFileManager等,獲取他們的實例通過[NSNotificationCenter?defaultCenter]和[NSFileManager?defaultManager]來獲取,其實這就是單例。
我們先看下函數(shù)void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);其中第一個參數(shù)predicate,該參數(shù)是檢查后面第二個參數(shù)所代表的代碼塊是否被調(diào)用的謂詞,第二個參數(shù)則是在整個應(yīng)用程序中只會被調(diào)用一次的代碼塊。dispach_once函數(shù)中的代碼塊只會被執(zhí)行一次,而且還是線程安全的。
? ? ? ?接下來我們來實現(xiàn)自己的單例,這里有一個SchoolManager類,為這個類實現(xiàn)單例
[cpp] view plain copy
使用就按照如下方式獲取唯一實例即可:
[cpp] view plain copy
轉(zhuǎn)載于:https://my.oschina.net/LangZiAiFer/blog/126982
總結(jié)
- 上一篇: 广播系统android安全:flag F
- 下一篇: java实现选择排序