设计模式之单利模式 (Objective-c)

     根据苹果官方的文档,单利模式是通过重写release,retain,retainCount,autoRelease,allocWithZone和copyWithZone等方法实现的,为了加强引用,建议在release、retain、autorelease里面做一些内部的调用次数监控,一旦外部调用不平衡就发出警告。

下面就是一个小的demo:

单利头文件

#import <Foundation/Foundation.h>

@interface Singleton : NSObject
{
    NSString *_name;
    NSString *_psw;
}
@property (nonatomic,retain)NSString* name;
@property (nonatomic,retain)NSString* psw;
+(Singleton*)getInstance;
@end

实现文件

#import "Singleton.h"

static  Singleton *instance = nil;
@implementation Singleton

@synthesize name = _name;
@synthesize psw = _psw;
+(Singleton*)getInstance{
    @synchronized(self) {
        if (!instance) {
            instance = [[super allocWithZone:NULL] init];
        }
    }
   
    return instance;
}


- (id)init
{
    if (self = [super init]) {
        return self;
    }
}
+(id)allocWithZone:(NSZone *)zone
{
    return [[self getInstance] retain];
}

-(id)copyWithZone:(NSZone *)zone
{
    return self;
}
-(id)retain
{
    return self;
}

-(NSUInteger)retainCount
{
    return NSUIntegerMax;
}

- (oneway void)release{//oneway关键字只用在返回类型为void的消息定义中, 因为oneway是异步的,其消息预计不会立即返回。
    //什么都不做
}
-(NSString*)description
{
    return [NSString stringWithFormat:@"Singleton:%@,%@",_name,_psw];

}
- (void)dealloc {
    [_name release];
    [_psw release];
    [super dealloc];
}

@end

测试代码:

 Singleton *sl = [[Singleton alloc] init];
        sl.name = @"chengliqun";
        sl.psw = @"root";
        
        Singleton *sl2 = [Singleton getInstance];
        sl2.name = @"chengliqun2";
        sl2.psw = @"root2";
        
        NSLog(@" %@",sl);
        NSLog(@" %@",sl2);
        [sl2 release];
        [sl release];
输出结果:
14:50:04.064 Singleton[835:14503]  Singleton:chengliqun2,root2
14:50:04.069 Singleton[835:14503]  Singleton:chengliqun2,root2

从输出结果可以判断,确实实现了单例模式

你可能感兴趣的:(单例模式,oc,objective-c)