Java 用enum 实现一个单列
//enum class
public eumn SingleTonEnum {
SINGLETON
private SingletonClass singleton ;
SingleTon(){
this.singleton = new SingletonClass ()
}
//get singleton
public SingletonClass getSingleTon(){
return this.singleton ;
}
}
//singleton class
class SingletonClass {
int i = 0;
public SingletonClass() {
System.out.println("SingletonClass被初始化 " + ++i + " 次");
}
}
//main test
class SingletonTest {
public static void main(String[] args) {
SingletonClass instance1 = Singleton.INSTANCE.getInstance();
SingletonClass instance2 = Singleton.INSTANCE.getInstance();
System.out.println("instance1 == instance2: " + (instance1 == instance2));
}
}
java 懒汉式实现singleton
懒汉式是延迟加载的,当需要用的时候才会创建实列,可以节省不必要的资源开销,但也存在线不安全问题
// 单例模式的懒汉实现1--线程不安全
class SingletonLazy1 {
private static SingletonLazy1 singletonLazy;
private SingletonLazy1() {
}
public static SingletonLazy1 getInstance() {
if (null == singletonLazy) {
try {
// 模拟在创建对象之前做一些准备工作
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
singletonLazy = new SingletonLazy1();
}
return singletonLazy;
}
}
// 单例模式的懒汉实现2--线程安全
// 通过设置同步方法,效率太低,整个方法被加锁
class SingletonLazy2 {
private static SingletonLazy2 singletonLazy;
private SingletonLazy2() {
}
public static synchronized SingletonLazy2 getInstance() {
try {
if (null == singletonLazy) {
// 模拟在创建对象之前做一些准备工作
Thread.sleep(1000);
singletonLazy = new SingletonLazy2();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return singletonLazy;
}
}
// 单例模式的懒汉实现3--线程安全
// 通过设置同步代码块,效率也太低,整个代码块被加锁
class SingletonLazy3 {
private static SingletonLazy3 singletonLazy;
private SingletonLazy3() {
}
public static SingletonLazy3 getInstance() {
try {
synchronized (SingletonLazy3.class) {
if (null == singletonLazy) {
// 模拟在创建对象之前做一些准备工作
Thread.sleep(1000);
singletonLazy = new SingletonLazy3();
}
}
} catch (InterruptedException e) {
// TODO: handle exception
}
return singletonLazy;
}
}
//单例模式的懒汉实现5--线程安全
//通过设置同步代码块,使用DCL双检查锁机制
//使用双检查锁机制成功的解决了单例模式的懒汉实现的线程不安全问题和效率问题
//DCL 也是大多数多线程结合单例模式使用的解决方案
class SingletonLazy5 {
private static volatile SingletonLazy5 singletonLazy;
private SingletonLazy5() {
}
public static SingletonLazy5 getInstance() {
try {
if (null == singletonLazy) {
// 模拟在创建对象之前做一些准备工作
Thread.sleep(1000);
synchronized (SingletonLazy5.class) {
if(null == singletonLazy) {
singletonLazy = new SingletonLazy5();
}
}
}
} catch (InterruptedException e) {
// TODO: handle exception
}
return singletonLazy;
}
}
java 饿汉式实现singleton
饿汉式是立即加载,声明并创建按类为静态类,并返回改类,在类加载之前就已经创建class实例。缺点是无论该类使用与否都会占用资源,如果类本身占用的资源很大就不适合,适合于占用资源少的class
class SingletonHungary {
private static SingletonHungary singletonHungary = new SingletonHungary();
//将构造器设置为private禁止通过new进行实例化
private SingletonHungary() {
}
public static SingletonHungary getInstance() {
return singletonHungary;
}
}
原文参照:
链接:饿汉式-懒汉式
链接:enum实现