1.策略模式的类图:
2.单例模式的用途:
在项目中有很多资源都是唯一共享的。单例模式可以实现这些资源在整个项目中唯一的存在,并方便使用者调用资源。
3.单例模式的优点:
(1)方便了全局资源的唯一和共享
4.单例模式的缺点:
(1)在整个项目周期内都占用内存。
5.单例模式的要点:
(1)多线程同步问题,必须保证单例的静态实例获取方法是多线程安全的,往往会在此方法内加上编程语言的线程同步函数,这样就会消耗一些时间来进行同步。为了性能,我们可以使用双重检查加锁,来减少获取实例的函数中对同步的使用。
public class Singleton
{
private volatile static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance()
{
if(uniqueInstance == null)
{
synchronized(Singleton.class)
{
if(uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
6.单例模式的实例:
(1)Objective-C代码:
+ (id)getSingletonInstance
{
static Singleton *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (instance == nil)
{
instance = [[Singleton alloc] init];
}
});
return instance;
}
- (void)dealloc
{
[super dealloc];
}
- (id)init
{
self = [super init];
if (nil == instance)
{
}
return instance;
} (2)其他语言的代码慢慢记录
本文介绍了单例模式的用途、优点及缺点,并通过Java和Objective-C提供了实现示例。单例模式确保类仅有一个实例存在,并提供一个全局访问点。
2335

被折叠的 条评论
为什么被折叠?



