饿汉式(静态常量)
package com.yundi.atp.dp.singleton;
public class SingletonOne {
private SingletonOne() {
}
private final static SingletonOne INSTANCE = new SingletonOne();
public static SingletonOne getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
SingletonOne instance = SingletonOne.getInstance();
System.out.println(instance);
}
}
饿汉式(静态代码块)
package com.yundi.atp.dp.singleton;
public class SingletonTwo {
private SingletonTwo() {
}
private static SingletonTwo INSTANCE;
static {
INSTANCE = new SingletonTwo();
}
public static SingletonTwo getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
SingletonTwo instance = SingletonTwo.getInstance();
System.out.println(instance);
}
}
懒汉式(线程不安全)
package com.yundi.atp.dp.singleton;
public class SingletonThree {
private SingletonThree() {
}
private static SingletonThree INSTANCE;
public static SingletonThree getInstance() {
if (null == INSTANCE) {
INSTANCE = new SingletonThree();
}
return INSTANCE;
}
public static void main(String[] args) {
SingletonThree instance = SingletonThree.getInstance();
System.out.println(instance);
}
}
懒汉式(线程安全,同步方式)
package com.yundi.atp.dp.singleton;
public class SingletonFour {
private SingletonFour() {
}
private static SingletonFour INSTANCE;
public static synchronized SingletonFour getInstance() {
if (null == INSTANCE) {
INSTANCE = new SingletonFour();
}
return INSTANCE;
}
public static void main(String[] args) {
SingletonFour instance = SingletonFour.getInstance();
System.out.println(instance);
}
}
双重检查
package com.yundi.atp.dp.singleton;
public class SingletonFive {
private SingletonFive() {
}
private static volatile SingletonFive INSTANCE;
public static SingletonFive getInstance() {
if (null == INSTANCE) {
synchronized (SingletonFive.class) {
if (null == INSTANCE) {
INSTANCE = new SingletonFive();
}
}
}
return INSTANCE;
}
public static void main(String[] args) {
SingletonFive instance = SingletonFive.getInstance();
System.out.println(instance);
}
}
静态内部类
package com.yundi.atp.dp.singleton;
public class SingletonSix {
private SingletonSix() {
}
private static class Singleton {
private final static SingletonSix INSTANCE = new SingletonSix();
}
public static SingletonSix getInstance() {
return Singleton.INSTANCE;
}
public static void main(String[] args) {
SingletonSix instance = SingletonSix.getInstance();
System.out.println(instance);
}
}
枚举
package com.yundi.atp.dp.singleton;
public enum SingletonSeven {
INSTANCE;
public void test1(){
System.out.println("hello world!");
}
public static void main(String[] args) {
SingletonSeven instance = SingletonSeven.INSTANCE;
SingletonSeven instance1 = SingletonSeven.INSTANCE;
System.out.println("instance:"+instance.hashCode());
System.out.println("instance1:"+instance1.hashCode());
}
}
|