单例模式这么理解呢
如学生类创建的学生都是同一个人,这是:单例模式
ViewController.m
#import "ViewController.h"
#import "Student.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*
设计模式(用来解决编程某些特定问题) -- 单例模式
单例模式
什么时候使用单例模式?
在一个工程中,一些类只需要一个实例变量,我们就可以将这些类设计成单例模式
单例模式的作用?
当一个'类A'被设计成单例模式时,由'类A'构造出的实例对象之于其他类来讲为全局实例对象,即在每一个类中由'A'构造出的实例对象,都未相同的对象。
单例模式的实现思路:一个类只能创建一个实例和一个获得该实例的方法。
*/
Student *st1 = [Student shareInstance];
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
==========================================================================Student.h
#import <Foundation/Foundation.h>
@interface Student : NSObject
//1.在要被设计成单例的类的.h文件中声明一个构造单例方法
+(Student *)shareInstance ;
@end
==========================================================================Student.m
#import "Student.h"
//声明一个静态实例对象,只会在第一次执行
static Student *st = nil;
@implementation Student
//2.实现该方法
+(Student *)shareInstance
{
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产生新的对象
//为了防止copy产生出新的对象,需要实现NSCopying协议
//-(id)copyWithZone:(NSZone *)zone
//{
// return self;
//}
@end