首页 > 代码库 > 单例模式

单例模式

1 懒汉式

package com.m01.program.maven_1;public class Singleton2 {    private Singleton2(){}    private static Singleton2 s=null;    public static  Singleton2 getSingleton2(){        if(s==null){            synchronized (Singleton2.class) {                if(s==null){                    s=new Singleton2();                }            }        }        return s;    }}

2 饱汉式

package com.m01.program.maven_1;public class SingletonTest1 {    private SingletonTest1(){}    private static  SingletonTest1 s=new SingletonTest1();    public static SingletonTest1 getSingletonTest1(){        return s;    }}

3 通过静态内部类

package com.m01.program.maven_1;public class Singleton3 {    private static class getSingle{         private static Singleton3  s=new Singleton3();    }    private Singleton3(){}    public static Singleton3 getSingleton3(){        return getSingle.s;    }}

4 通过枚举

package com.m01.program.maven_1;public enum Singleton5 {    INSTANCE;    public void doWhat(){        System.out.println("OOXX");    }}

5 通过静态代码块

package com.m01.program.maven_1;public class Singleton3 {     static {          s=new Singleton3();    }    private Singleton3(){}    private static Singleton3 s;    public static Singleton3 getSingleton3(){        return s;    }}

 

单例模式