Cocoa的单态(singleton)设计模式
来源:互联网 发布:ios能用java开发吗 编辑:程序博客网 时间:2024/05/19 13:19
http://www.cocoachina.com/b/?p=256
如果你准备写一个类,希望保证只有一个实例存在,同时可以得到这个特定实例提供服务的入口,那么可以使用单态设计模式。单态模式在Java、C++中很常用,在Cocoa里,也可以实现。
由于自己设计单态模式存在一定风险,主要是考虑到可能在多线程情况下会出现的问题,因此苹果官方建议使用以下方式来实现单态模式:
- static MyGizmoClass *sharedGizmoManager = nil;
- + (MyGizmoClass*)sharedManager
- {
- @synchronized(self) {
- if (sharedGizmoManager == nil) {
- [[self alloc] init]; // assignment not done here
- }
- }
- return sharedGizmoManager;
- }
- + (id)allocWithZone:(NSZone *)zone
- {
- @synchronized(self) {
- if (sharedGizmoManager == nil) {
- sharedGizmoManager = [super allocWithZone:zone];
- return sharedGizmoManager; // assignment and return on first allocation
- }
- }
- return nil; //on subsequent allocation attempts return nil
- }
- - (id)copyWithZone:(NSZone *)zone
- {
- return self;
- }
- - (id)retain
- {
- return self;
- }
- - (unsigned)retainCount
- {
- return UINT_MAX; //denotes an object that cannot be released
- }
- - (void)release
- {
- //do nothing
- }
- - (id)autorelease
- {
- return self;
- }
- Cocoa的单态(singleton)设计模式
- Cocoa的单态(singleton)设计模式
- Cocoa的单态(singleton)设计模式
- Cocoa的单例(singleton)设计模式
- iOS的单态(singleton)设计模式
- Singleton(单态设计模式)
- 设计模式--单态(Singleton)
- Java设计模式:Singleton(单态模式)
- 设计模式笔记:单态模式(Singleton)
- 设计模式之Singleton(单态模式)
- 设计模式之Singleton(单态模式)
- 设计模式之Singleton(单态模式)
- 设计模式学习----Singleton单态模式
- 设计模式 -- Singleton单态模式
- Java的单例设计模式Singleton
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- 设计模式之Singleton(单态)
- STL学习系列之三——list序列容器
- 设计模式-OOD的设计原则(4)-"接口隔离原则"
- 设计模式-OOD的设计原则(5)-"合成聚合复用原则"
- SQL Server 2000 服务器网络实用工具和客户端网络实用工具的调用
- 转载 Windows下 JAVA_HOME PATH CLASSPATH 三个变量的配置
- Cocoa的单态(singleton)设计模式
- 常见Web技术之间的关系,你了解多少?
- 我大学剩下一年半的生活(六)——pythonchallenge之level5
- 【学习笔记】WP7语音API MircoPhone
- windbg使用
- 信号处理中频率的概念
- 微软等面试100题第一题
- 对象池化技术 org.apache.commons.pool
- 文件传输