应用场合:有些对象只需要一个,比如:配置文件,工具类,线程池、缓存、日志对象等;
常用的有懒汉模式和饿汉模式两种单例模式;(构造方法:私有化,不允许外部直接创建)
区别:
【饿汉模式】- 类加载的时候就创建了类的实例,所以加载类时比较慢,但运行时获取对象的速度比较快;线程安全;
/**
* 单例模式 - 饿汉模式
* 类加载时就创建类的实例
* @author chenj
*/
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
public static void main(String args[]){
Singleton st1 = Singleton.instance;
Singleton st2 = Singleton.instance;
if(st1 == st2){
System.out.println("s1和s2是同一个实例");
} else {
System.out.println("s1和s2不是同一个实例");
}
}
}
【懒汉模式】- 类使用的时候才创建类的实例,所以加载类时比较快,但运行时获取对象的速度比较慢;线程不安全;
/**
* 单例模式 - 懒汉模式
* 类使用时才创建类的实例
* @author chenj
*/
public class Singleton {
private static Singleton instance;
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
public static void main(String args[]){
Singleton st1 = Singleton.instance;
Singleton st2 = Singleton.instance;
if(st1 == st2){
System.out.println("s1和s2是同一个实例");
} else {
System.out.println("s1和s2不是同一个实例");
}
}
}
本文介绍了单例模式的应用场合及其两种实现方式:饿汉模式和懒汉模式。饿汉模式在线程安全下于类加载时创建实例,而懒汉模式则在类使用时创建实例,但存在线程安全问题。
2321

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



