OC语言单例模式与Swift单例模式

开发中,我们经常使用单例模式,编写单例,为什么要写单例呢

事实上,单例也是一种设计模式,它在整个生命周期中都存在,且项目中很多地方可以共用用同一方法,为了避免在用到这一方法的地方的时候都要实例化方法,也避免后期不好维护,所以建议使用单例,OC情况下,使用单例时要使用线程,保证这个方法在项目中只被实例化一次


OC单例

@interface className : NSObject
@end
 
@implementation className
 
+ (instancetype)sharedInstance {
     static id *sharedInstance = nil;
     static dispatch_once_t onceToken;
     
     dispatch_once(&onceToken, ^{
         sharedInstance = [[self alloc] init];
     });
     return  sharedInstance;
}
 
@end

swift单例

class className:NSObject{

    

    //单例创建

    //工具类单例

    staticlet name :className= {

        let name =className()

        

        returnname

    }()


猜你喜欢

转载自blog.csdn.net/qq_33298465/article/details/75057525
今日推荐