首页 > 代码库 > 单例模式
单例模式
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; }}
单例模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。