public class Singleton {
/* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
private static Singleton instance = null;
/* 私有构造方法,防止被实例化 */
private Singleton() {
}
/* 1:懒汉式,静态工程方法,创建实例 */
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Singleton.getInstance().method();
/*2.懒汉式变种,解决线程安全问题**/
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
/*加上synchronized,但是每次调用实例时都会加载**/
public static Singleton getInstance() {
synchronized (Singletonclass) {
if (instance == null) {
instance = new Singleton();
}
}
return instance;
}
Singleton.getInstance().method();
/*3.双重锁定:只在第一次初始化的时候加上同步锁*/
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singletonclass) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
instance = new Singleton();
Singleton.getInstance().method();
public class SingletonInner {
/**
* 内部类实现单例模式
* 延迟加载,减少内存开销
*
* @author xuzhaohu
*
*/
private static class SingletonHolder {
private static SingletonInner instance = new SingletonInner();
}
/**
* 私有的构造函数
*/
private SingletonInner() {
}
public static SingletonInner getInstance() {
return SingletonHolderinstance;
}
protected void method() {
Systemoutprintln("SingletonInner");
}
}
SingletonInner.getInstance().method();
/**
* @function:单例模式枚举实现
* @author xuzhaohu
*
*/
public enum SingletonEnum {
/**
* 从Java5开始支持;
* 无偿提供序列化机制;
* 绝对防止多次实例化,即使在面对复杂的序列化或者反射攻击的时候;
*/
instance;
private String others;
SingletonEnum() {
}
public void method() {
Systemoutprintln("SingletonEnum");
}
public String getOthers() {
return others;
}
public void setOthers(String others) {
thisothers = others;
}
}
SingletonEnum.instance.method();
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有