单例模式(oc)
//主函数 main.m #import <Foundation/Foundation.h> #import "Singleton.h" int main(int argc, const char * argv[]) { @autoreleasepool { Singleton *sing1= [Singleton shareInstance]; Singleton *sing2=[Singleton shareInstance]; Singleton *sing3=[Singleton new]; Singleton *sing4=[[Singleton alloc]init]; Singleton *sing5=[sing4 copy]; NSLog(@"%@",sing1); NSLog(@"%@",sing2); NSLog(@"%@",sing3); NSLog(@"%@",sing4); NSLog(@"%@",sing5); } return 0; } //Singleton.h文件 #import <Foundation/Foundation.h> @interface Singleton : NSObject<NSCopying> +(Singleton *)shareInstance; @end //Singleton.m文件 #import "Singleton.h" @implementation Singleton static Singleton *singleton; //单例方法 +(Singleton *)shareInstance{ if (singleton==nil) { singleton=[[Singleton alloc]init]; } return singleton; } //单例方法 初始化 +(instancetype)allocWithZone:(struct _NSZone *)zone{
//懒加载 if (singleton==nil) { singleton=[super allocWithZone:zone]; } return singleton; } //单例方法 复制 -(id)copyWithZone:(NSZone *)zone{ return self; } @end