单例模式
Posted 夏末的秋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式相关的知识,希望对你有一定的参考价值。
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; } }
以上是关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章