您的位置:首页 > 其它

单例模式--确保一个类只有一个实例,并提供一个全局访问点。

2017-02-05 22:41 316 查看
一、定义:单件模式--确保一个类只有一个实例,并提供一个全局访问点。

二、方式:

1.懒汉式

/**
*
* @author Kevintan
* 经典的单件模式的实现,懒汉式
* synchronized 处理多线程的同步问题。
* 缺点:降低了性能,不利于程序频繁的调用
* 适用场景:性能对应用程序不是很关键。
*/
public class Singleton1 {
private static Singleton1 uniqueInstance ;

private Singleton1() {}

public static synchronized Singleton1 getInstance(){
if (uniqueInstance ==  null) {
uniqueInstance = new Singleton1();
}
return uniqueInstance;
}

}

2.饿汉式

/**
*
* @author Kevintan
* 急切实例化,饿汉式
* 适用于:应用程序总是创建并使用单件实例或创建和运行时的负担不太繁重。
* 缺点:不能用于频繁创建或使用或耗费内存过大的程序中。
*/
public class Singleton2 {
private static Singleton2 uniqueInstance = new Singleton2();

private Singleton2() {}

public static Singleton2 getInstance(){
if (uniqueInstance ==  null) {
uniqueInstance = new Singleton2();
}
return uniqueInstance;
}

}


3.双重检索加锁


/**
*
* @author Kevintan
*双重检索加锁
*原理:首先检查是否实例已经创建了,如果尚未创建,“才”进行同步。
*这样一来,只有第一次创建实例时会同步。
*优点及适用于:帮助你大大减少时间耗费,提高性能
*/
public class Singleton3 {
private static volatile Singleton3 uniqueInstance ;

private Singleton3() {}

public static synchronized Singleton3 getInstance(){
if (uniqueInstance ==  null) {
synchronized (Singleton3.class) {
if (uniqueInstance ==  null) {
uniqueInstance = new Singleton3();
}
}
}
return uniqueInstance;
}

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式 singleton
相关文章推荐