package com.ygh.singleton;
/**
* 饿汉式单例类
* @author 夜孤寒
* @version 1.1.1
*/
public class HungerSingleton {
//将构造方法私有,外界类不能使用构造方法new对象
private HungerSingleton(){}
//创建一个对象
private static final HungerSingleton lazySinleton=new HungerSingleton();
//设置实例获取方法,返回实例给调用者
public static HungerSingleton getInstance(){
return lazySinleton;
}
}
package com.ygh.singleton;
/**
* 测试单例类
*
* @author 夜孤寒
* @version 1.1.1
*/
public class Test {
public static void main(String[] args) {
/*
* 构造方法私有化,不能够使用下面方式new对象
*/
//HungerSingleton hungerSingleton=new HungerSingleton();
//使用实例获取方法来获取对象
HungerSingleton h1=HungerSingleton.getInstance();
HungerSingleton h2=HungerSingleton.getInstance();
System.out.println(h1==h2);//true
}
}
package com.ygh.singleton;
/**
* 懒汉式单例类
* @author 夜孤寒
* @version 1.1.1
*/
public class LazySingleton {
//将构造方法私有,外界类不能使用构造方法new对象
private LazySingleton(){}
//创建一个对象,不为final
private static LazySingleton lazySingleton=null;
//设置实例获取方法,返回实例给调用者
public static LazySingleton getInstance(){
//当单例对象不存在,创建
if(lazySingleton==null){
lazySingleton=new LazySingleton();
}
//返回
return lazySingleton;
}
}
package com.ygh.singleton;
/**
* 测试单例类
*
* @author 夜孤寒
* @version 1.1.1
*/
public class Test {
public static void main(String[] args) {
/*
* 构造方法私有化,不能够使用下面方式new对象
*/
//LazySingleton lazySingleton=new LazySingleton();
//使用实例获取方法来获取对象
LazySingleton l1=LazySingleton.getInstance();
LazySingleton l2=LazySingleton.getInstance();
System.out.println(l1==l2);//true
}
}
import java.util.HashMap;
import java.util.Map;
/**
* 登记式单例类
* @author Administrator
*
*/
public class RegisterSingleton {
private static Map<String, RegisterSingleton> map = new HashMap<String, RegisterSingleton>();
static {
RegisterSingleton single = new RegisterSingleton();
map.put(single.getClass().getName(), single);
}
/*
* 保护的默认构造方法
*/
protected RegisterSingleton() {
}
/*
* 静态工厂方法,返还此类惟一的实例
*/
public static RegisterSingleton getInstance(String name) {
if (name == null) {
name = RegisterSingleton.class.getName();
System.out.println("name == null" + "--->name=" + name);
}
if (map.get(name) == null) {
try {
map.put(name, (RegisterSingleton) Class.forName(name).newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return map.get(name);
}
/*
* 一个示意性的商业方法
*/
public String about() {
return "Hello, I am RegSingleton.";
}
public static void main(String[] args) {
RegisterSingleton single3 = RegisterSingleton.getInstance(null);
System.out.println(single3.about());
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有