美文网首页
iOS设计模式(单例模式)

iOS设计模式(单例模式)

作者: hfzhangzhang | 来源:发表于2018-07-01 22:36 被阅读0次

    单例模式(Singleton)
    保证一个类仅有一个实例,并提供一个该实例的全局访问点。

    定义包含三层含义:一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须向整个系统提供这个实例。


    OC

    @interface ZZSingleton : NSObject
    + (instancetype)shareSingleton;
    @end
    
    
    @implementation ZZSingleton
    
    static ZZSingleton *shareSingleton = nil;
    
    + (instancetype)shareSingleton {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            shareSingleton = [[super allocWithZone:NULL] init];
        });
        return shareSingleton;
    }
    
    + (instancetype)allocWithZone:(struct _NSZone *)zone {
        return [ZZSingleton shareSingleton];
    }
    
    - (id)copyWithZone:(struct _NSZone *)zone {
        return [ZZSingleton shareSingleton];
    }
    
    @end
    
    
    #######
       ZZSingleton *one = [ZZSingleton shareSingleton];
        NSLog(@"one = %@", one);
        
        ZZSingleton *two = [ZZSingleton shareSingleton];
        NSLog(@"two = %@", two);
        
        ZZSingleton *three = [[ZZSingleton alloc] init];
        NSLog(@"three = %@", three);
        
        ZZSingleton *four = [[ZZSingleton alloc] init];
        NSLog(@"four = %@", [four copy]);
        
        ZZSingleton *five = [ZZSingleton new];
        NSLog(@"five = %@", five);
    

    相关文章

      网友评论

          本文标题:iOS设计模式(单例模式)

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