package cn.singleton;
import java.util.HashMap;
import java.util.Map;
/**
* 单例模式实现
* @author 姚伟楠
*
*/
public class Singleton {
/**
* 测试入口
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Object obj1=Object.getInstance();
Object obj2=Object.getInstance();
System.out.print("懒汉式:");
System.out.println(obj1==obj2);
Object1 obj3=Object1.getInstance();
Object1 obj4=Object1.getInstance();
System.out.print("饿汉式:");
System.out.println(obj3==obj4);
Object2 obj5=Object2.getInstance(Object2.class.getName());
Object2 obj6=Object2.getInstance(Object2.class.getName());
System.out.print("登记式:");
System.out.println(obj5==obj6);
}
}
/**
* 懒汉式单例(需要时候才实例化)
* @author 姚伟楠
*
*/
class Object{
private static Object instance=null;
private Object() {}
public static synchronized Object getInstance(){
if(null==instance)instance=new Object();
return instance;
}
}
/**
* 饿汉式(初始化类时候实例化)
* @author 姚伟楠
*
*/
class Object1{
private static Object1 instance=new Object1();
private Object1(){}
public static Object1 getInstance(){
return instance;
}
}
/**
* 登记式(内类存储实例并作登记,需要时直接按照登记号(类名)获取)
* @author 姚伟楠
*
*/
class Object2{
private static Map<String, Object2> instances=new HashMap<String, Object2>();
static{
Object2 instance=new Object2();
instances.put(Object2.class.getName(), instance);
}
/**
* 保证子类、同包、自身可以创建非单例实例
*/
protected Object2(){}
public static Object2 getInstance(String name){
if(null==name){
name = Object2.class.getName();
}
if(instances.get(name) == null) {
try {
instances.put(name, (Object2) Class.forName(name).newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return instances.get(name);
}
}