iOS中的单例

#import "Singleton.h"

@implementation Singleton

static Singleton *singleton = nil;

+ (Singleton *)shareSingleton
{
    @synchronized(self)
    {
        if (!singleton) {
            singleton = [[self alloc]init];
        }
        return singleton;
    }
}

+ (id)alloc
{
    @synchronized(self)
    {
        singleton = [super alloc];
        
        return singleton;
    }
}

@end

单例也是设计模式的一种,到目前为止一共总结的设计模式有三种:观察者模式、代理模式、单例模式。

通过写这个单例,明白了:

1.静态方法实例化一个类其实就是在本类中实例化自己,单例是指在整个软件中只有一个类实例存在,是全局使用的。

2.static关键字是在编译时初始化的,之后再运行到static那句代码时不会再初始化,作用域只在当前.m文件中,只要.m不销毁,static的变量就一直存在并保存其变量值。

 

 
 
posted @ 2015-06-07 20:39  Isabel_r  阅读(151)  评论(0编辑  收藏  举报