import java.util.*;
public class Main{
public static void main(String[] args){
System.out.println("饿汉式");
System.out.println(Singleton1.getInstance().toString());
System.out.println(Singleton1.getInstance().toString());
System.out.println("懒汉式");
System.out.println(Singleton2.getInstance().toString());
System.out.println(Singleton2.getInstance().toString());
System.out.println("静态内部类");
System.out.println(Singleton3.getInstance().toString());
System.out.println(Singleton3.getInstance().toString());
System.out.println("双检锁");
System.out.println(Singleton5.getInstance().toString());
System.out.println(Singleton5.getInstance().toString());
System.out.println(Singleton4.INSTANCE);
Singleton4.INSTANCE.anyMethod();
System.out.println(Singleton4.INSTANCE);
}
}
class Singleton1{
private static Singleton1 instance = new Singleton1();
private Singleton1(){};
// 饿汉式
public static Singleton1 getInstance(){
return instance;
}
}
class Singleton2{
private static Singleton2 instance;
private Singleton2(){};
// 懒汉式
public synchronized static Singleton2 getInstance(){
if (instance==null)
instance = new Singleton2();
return instance;
}
}
class Singleton3{
private Singleton3(){};
// 静态内部类
private static class Helper{
private static final Singleton3 instance = new Singleton3();
}
public static final Singleton3 getInstance(){
return Helper.instance;
}
}
// 枚举
enum Singleton4{
INSTANCE;
public void anyMethod(){
System.out.println("This is enum.");
}
}
class Singleton5{
private static Singleton5 instance;
private Singleton5(){};
// 懒汉式 双检锁
public static Singleton5 getInstance(){
if (instance==null){
synchronized(Singleton5.class){
if (instance==null)
instance = new Singleton5();
}
}
return instance;
}
}
单例模式
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...