完整版单例

2015-10-16  本文已影响55人  MTZ_上善若水

单例是一种设计模式,通过一个类方法获取到的实例是唯一的,它就是个单例。

static类型的全局变量的值是存储到全局静态区,所有对象的同一个static类型的全局变量的指针指向同一块空间,所以当静态存储区里面的值被修改时,所有对象里面的指针所指向的这块空间的值都被改变,static类型的全局变量的值可以实现对象之间数据共享

写单例类方法的规则:一般是以sharedXXX、defaultXXX、currentXXX的格式来创建

static SingleCase* singleCase = nil;//先声明一个全局静态变量

+ (SingleCase *)sharedSingleCase {

    @synchronized(self) {

        if (singleCase == nil) {

            singleCase = [[super allocWithZone:NULL] init];

        }

    }

    return singleCase;

}

另外一种方法也是常用的一种方法是GCD里面的一套API

+ (SingleCase *)sharedSingleCase {

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        singleCase = [[super allocWithZone:NULL] init];

    });

    return singleCase;

}

模仿系统写一个自己的单例

void TZ_dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {

    if (*predicate == 0) {

        *predicate = 1;

        if (block) {

            block();

        }

    }

}

+ (SingleCase *)sharedSingleCase {

    @synchronized(self) {

        TZ_dispatch_once(onceToken, ^{

            singleCase = [[super allocWithZone:NULL] init];

        });

    }

    return singleCase;

}

完整版单例需要实现的方法

+ (instancetype)allocWithZone:(struct _NSZone *)zone {

    return [SingleCase sharedSingleCase];

}

下面两个方法需要采用协议 <NSCopying, NSMutableCopying>

- (id)copyWithZone:(NSZone *)zone {

    return [SingleCase sharedSingleCase];

}

- (id)mutableCopyWithZone:(NSZone *)zone {

    return [SingleCase sharedSingleCase];

}

- (instancetype)retain {

    return self;

}

- (oneway void)release {

}

- (instancetype)autorelease {

    return self;

}

- (NSUInteger)retainCount {

    return NSUIntegerMax;

}

上一篇 下一篇

猜你喜欢

热点阅读