首页 > 代码库 > 设计模式-单例模式(Singleton)
设计模式-单例模式(Singleton)
恶汉式
package cn.foxeye.design.singleton; public class Singleton { private static Singleton instance = new Singleton(); public Singleton() { } public static Singleton getInstance() { return instance; } }
懒汉式
package cn.foxeye.design.singleton; public class Singleton2 { private static Singleton2 instance = null; private Singleton2() { } public static synchronized Singleton2 getInstance() { if (instance == null) { instance = new Singleton2(); } return instance; } }
双重检查加锁
package cn.foxeye.design.singleton; public class Singleton3 { private static Singleton3 instance = null; private Singleton3() { } public static Singleton3 getInstance() { if(instance == null) { synchronized (Singleton3.class) { if(instance == null) { instance = new Singleton3(); } } } return instance; } }
Lazy initialization holder class模式
package cn.foxeye.design.singleton; public class Singleton4 { private Singleton4() { } private static class SingletonHolder { private static Singleton4 instance = new Singleton4(); } public static Singleton4 getInstance() { return SingletonHolder.instance; } }
枚举式
package cn.foxeye.design.singleton; public enum Singleton5 { uniqueInstance; private String name; private String sex; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
设计模式-单例模式(Singleton)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。