美文网首页
单例模式

单例模式

作者: 红茶绅士 | 来源:发表于2017-04-07 16:03 被阅读2次

    单例模式的作用

    可以保证在程序运行过程中,一个类只有一个实例,而且该实例易于供外界访问
    从而方便的控制了实例个数,并节约系统资源

    单例模式的使用场合

    在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次)

    实现示例

    @interface User : NSObject <NSCopying, NSMutableCopying>
    
    + (instancetype)shareUser;
    
    @end
    
    @implementation User
    
    static User *_instance;
    
    + (instancetype)allocWithZone:(struct _NSZone *)zone {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [super allocWithZone:zone];
        });
        return _instance;
    }
    
    + (instancetype)shareUser {
        return [[self alloc] init];
    }
    
    - (id)copyWithZone:(NSZone *)zone {
        return _instance;
    }
    
    - (id)mutableCopyWithZone:(NSZone *)zone {
        return _instance;
    }
    @end
    

    相关文章

      网友评论

          本文标题:单例模式

          本文链接:https://www.haomeiwen.com/subject/wcmhattx.html