您的位置:首页 > 移动开发 > Objective-C

Objective-C语言——单例模式

2016-01-02 17:11 447 查看
Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject

//在要被设计成单例的类的.h 文件中声明一个构造单例方法
+(Student *)shateInstance;

@end


Student.m

#import "Student.h"
static Student *st = nil;

@implementation Student
//实现该方法
+(Student *)shateInstance
{
if (st == nil) {
st = [[Student alloc] init];
}
return st;

}

//为了防止 alloc 或 new 创建新的实例变量
+(id)allocWithZone:(struct _NSZone *)zone
{
/*
关于@synchronized(self)
@synchronized 的作用是创建一个互斥锁,保证此时没有其他线程对 self 对象进行修改
这个是 Objective-C 的锁令牌,防止 self 对象在同一时间被其他线程访问,起到线程保护作用,一般在公用变量的时候使用,例如单例模式 或者 操作类的 static 变量中使用
*/
@synchronized(self) {
if (st == nil) {
st = [super allocWithZone:zone];
}
}
return st;

}

//为了防止 copy 产生出新的对象,需要实现 NSCopying 协议
-(id)copyWithZone:(NSZone *)zone
{
return self;
}

@end


ViewController.m

#import "ViewController.h"
#import "Student.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

/*
设计模式(用来解决编程某些特定问题)————单例模式

单例模式
什么时候使用单例模式?
在一个工程中,一些类只需要一个实例变量,我们就可以将这些设计成单例模式

单例模式的作用?
当一个‘类 A’被设计成单例模式时,由‘类 A’构造出得实例对象之于其他类来讲为全局实例对象,即在每一个类中由'A'构造出实例对象,都未相同的对象。

单例模式的实现思路:一个类只能创建一个实例和一个获得该实例的方法。

*/

Student *st1 = [Student shateInstance];
Student *st2 = [[Student alloc] init];

Student *st3 = [st2 copy];

if (st2 == st3) {
NSLog(@"st2 == st3");
} else {
NSLog(@"st2 != st3");
}

}

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

@end


运行结果

2016-01-02 17:09:42.051 OC_LX_10_01[2103:41264] st2 == st3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: