Objective-C语言——单例模式
2016-01-02 17:11
447 查看
Student.h
Student.m
ViewController.m
运行结果
2016-01-02 17:09:42.051 OC_LX_10_01[2103:41264] st2 == st3
#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
相关文章推荐
- Objective-C语言——Protocol协议
- Objective-C语言——Extension延展
- C#中var、int、object性能比较
- C#中var、int、object性能比较
- Objective-C语言——Category类目
- ES6学习——新的语法:对象字面量扩展(Object Literal Extensions)
- Objective-C轻量级泛型
- [2]姥爷幽默谈Objective-C(数组和字典)
- Super Object Toolkit (支持排序)
- Objective-C History
- Objective-c语言_错误(视图多重关联)
- setValue: forKey 和 setObject: forkey的区别
- NSDictionary使用 ... enumerateKeysAndObjectsUsingBlock
- 【Objective-C学习记录】第三十天
- [Object C]_[初级]_[Object C之内存管理]
- 【Objective-C学习记录】第二十九天
- NSObject + NSCoding Category
- Objective-C之KVC、KVO
- Thread的join()方法和Object的wait(),notify(),notifyAll()方法
- Git CMD - show: Show various types of objects