设计模式-单例

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


@end

@interface SingleTonBase : NSObject

@property (copy,readwrite) NSString* MyName;

+(instancetype)SharedInstance;
@end
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    SingleTonBase* m1 = [SingleTonBase SharedInstance];/*SharedInstance->init*/
    SingleTonBase* m2 = [[SingleTonBase alloc] init];  /*allocWithZone->SharedInstance->init->init*/
    SingleTonBase* m3 = [m2 copy];                     /*copy*/
    SingleTonBase* m4 = [SingleTonBase alloc];         /*allocWithZone->SharedInstance->init*/
    SingleTonBase* m5 = [SingleTonBase new];           /*allocWithZone->SharedInstance->init->init*/
    SingleTonBase* m6 = [m2 mutableCopy];              /*mutableCopy*/
    /*能编译,但访问成员变量的时候,崩溃。
    SingleTonBase* m7 = [SingleTonBase copy];*/
    NSLog(@"%p,%p,%p,%p,%p,%p",m1,m2,m3,m4,m5,m6);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

static SingleTonBase* Instance = nil;
@implementation SingleTonBase
{
    
}

-(instancetype)init
{
    if (Instance) {
        return Instance;
    }
    if (self = [super init]) {
        self.MyName = @"default name";
    }
    return self;
}

+(instancetype)SharedInstance
{
    static dispatch_once_t one;
    dispatch_once(&one, ^{
        Instance = [[super allocWithZone:nil]init];
    });
    return Instance;
}

+(id)allocWithZone:(struct _NSZone *)zone
{
    return [self SharedInstance];
}
-(id)copy
{
    return self;
}
-(id)mutableCopy
{
    return self;
}
@end

总结下:

1,实现起来比c++要复杂,考虑的情况挺多,这个写法貌似是官方提供的。

2,非arc模式没有考虑

3,好像不能像c++声明静态的类成员变量。

参考:http://blog.csdn.net/a451493485/article/details/8624990


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值