单例

#import <Foundation/Foundation.h>

@interface Student : NSObject
@property(retain,nonatomic)NSString *name;
@property(assign,nonatomic)int age;


//设计单利模式
//+(类名*)shareXXX
//        defaultXXX
//        xxx
+(Student *)shareStudent;


@end

#import "Student.h"
@implementation Student
+(Student *)shareStudent
{
    //被static修饰的变量只会被初始化一次
    static Student *stu=nil;
    if (stu==nil) {
        //如果学生对象为空,就初始化学生对象
        stu=[[Student alloc]init];
    }
    return stu;
    
}
@end


#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        //调用单例方法
        //通过调用单例方法,返回的为同一个对象
        //Student *stu=[Student shareStudent];是单例模式的创建对象的方法
     Student *stu=[Student shareStudent];
     stu.name=@"xiaowang";
        
     Student *stu2=[Student shareStudent];
     NSLog(@"%@", stu2.name);
        
    
        
        
    }
    return 0;
}
原文地址:https://www.cnblogs.com/y16879w/p/4482027.html