IOS-DesignPattern-Singleton

来源:互联网 发布:win10 64位安装mysql 编辑:程序博客网 时间:2024/05/16 07:51

1、SingletonDemo.h

#import <Foundation/Foundation.h>@interface SingletonDemo : NSObject+(instancetype)shareSingletonDemo;//get instance method@end

2、SingletonDemo.m

#import "SingletonDemo.h"@implementation SingletonDemo//静态变量static SingletonDemo *_instance =   nil;//作用:加载类//什么时候调用:每次程序一启动,就会把所有的类加载进内存+(void)load{    NSLog(@"%s",__func__);    _instance   =   [[self alloc] init];}//get instance+(instancetype)shareSingletonDemo{    return _instance;}//reload alloc method+(instancetype)alloc{    //when the alloc method is being called,if the "_instance" is not nil then raise exception.    if(_instance)    {        NSException*    excp    =   [NSException exceptionWithName:@"NSInternalInconsistencyException"reason:@"There can only be one UIApplication instance" userInfo:nil];        [excp raise];    }    return [super alloc];}@end

3、测试代码

//[[SingletonDemo alloc] init];//The wrong way to call singleton instance    SingletonDemo*  single  =   [SingletonDemo  shareSingletonDemo];//the right way to call singleton instance    NSLog(@"%@",single);
0 0
原创粉丝点击