单例模式
什么时候使用单例模式?
在一个工程中,一些类只需要一个实例变量,我们就可以将这些类设计成单例模式
单例模式的作用?
当一个'类A'被设计成单例模式时,由'类A'构造出的实例对象之于其他类来讲为全局实例对象,即在每一个类中由'A'构造出的实例对象,都未相同的对象。
打印结果:
什么时候使用单例模式?
在一个工程中,一些类只需要一个实例变量,我们就可以将这些类设计成单例模式
单例模式的作用?
当一个'类A'被设计成单例模式时,由'类A'构造出的实例对象之于其他类来讲为全局实例对象,即在每一个类中由'A'构造出的实例对象,都未相同的对象。
单例模式的实现思路:一个类只能创建一个实例和一个获得该实例的方法。
#import <Foundation/Foundation.h>
@interface Teacher : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign)NSUInteger *age;
+(Teacher *)getInstance;//获得全局实例的类方法
@end
#import "Teacher.h"
//1.创建一个全局实例,并初始化为nil
static Teacher *teacher = nil;
@implementation Teacher
//2.实现方法,并返回单一一个对象
+(Teacher *)getInstance
{
if (teacher == nil)
{
teacher = [[Teacher alloc]init];
}
return teacher;
} //全局变量的单例模式不需要释放
//3.为了防止通过alloc或new创建新的实例,需要重写allocWithZone方法
+(id)allocWithZone:(struct _NSZone *)zone
{
if (teacher == nil)
{
teacher = [[super allocWithZone:zone] init];
}
return teacher;
}
//4.为了防止copy创建新的实例,重写copyWithZone
-(id)copyWithZone:(NSZone *)zone
{
return self;
}
@end
#import "ViewController.h"
#import "Teacher.h" //在main函数测试一下
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Teacher *t1 = [[Teacher alloc]init];
Teacher *t2 = [Teacher getInstance];
Teacher *t3 = [Teacher getInstance];
Teacher *t4 = [t3 copy];
NSLog(@"%p",t1);
NSLog(@"%p",t2);
NSLog(@"%p",t3);
NSLog(@"%p",t4);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
打印结果:
2015-12-22 15:06:10.868 copy-oc-10-book-01[2809:132831] 0x7fdf00de1dc0
2015-12-22 15:06:10.869 copy-oc-10-book-01[2809:132831] 0x7fdf00de1dc0
2015-12-22 15:06:10.869 copy-oc-10-book-01[2809:132831] 0x7fdf00de1dc0
2015-12-22 15:06:10.869 copy-oc-10-book-01[2809:132831] 0x7fdf00de1dc0
打印出的结果为四个相等的数,即这四个对象的内存地址是一样,即为同一对象,只创建分配内存了一次,这就确保了应用中的一个特定类有且仅有一个实例(对象),经常用于设计约束或者为了控制对有限资源的访问.