單例,即是在整個(gè)項(xiàng)目中,這個(gè)類的對(duì)象只能被初始化一次。
比如系統(tǒng)的通知中心:
[NSNotificationCenter defaultCenter]
那么,單例有什么好處吶?
You obtain the global instance from a singleton class through a factory method. The class lazily creates its sole instance the first time it is requested and thereafter ensures that no other instance can be created. A singleton class also prevents callers from copying, retaining, or releasing the instance. You may create your own singleton classes if you find the need for them. For example, if you have a class that provides sounds to other objects in an application, you might make it a singleton.
簡(jiǎn)單來說:全局可用,線程安全!
打個(gè)比方說:我們有一款播放視頻的APP,但是我不能為每一個(gè)視頻文件都創(chuàng)建一個(gè)播放器吧?我們只需要?jiǎng)?chuàng)建一個(gè)播放器,去播放我們需要看的視頻,而這個(gè)播放器就可以稱為“單例播放器”,全局可用,保證其唯一性。我們播放其中一個(gè)視頻的時(shí)候,不能同時(shí)播放其他視頻,線程安全。
那么我們創(chuàng)建單例怎么去創(chuàng)建吶,下面有兩種方法:
1:
static NFDbManager *DefaultManager = nil;
+ (NFDbManager *)defaultManager {
if (!DefaultManager) DefaultManager = [[self allocWithZone:NULL] init];
return DefaultManager;
}
2:
+ (NFDbManager *)sharedManager
{
static NFDbManager *sharedAccountManagerInstance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
sharedAccountManagerInstance = [[self alloc] init];
});
return sharedAccountManagerInstance;
}
開發(fā)過程中會(huì)遇到很多這樣全局唯一的,那么我們就可以創(chuàng)建一個(gè)單例對(duì)象。