设计模式之单例模式三种实现

来源:互联网 发布:手机短信恢复 软件 编辑:程序博客网 时间:2024/05/22 15:01
package com.mw.mbox.boss.demo;


/**
 * 懒汉式
 * @author niwei
 * 懒汉式单例类.在第一次调用的时候实例化 
 */
public class Sinleton {
//私有的默认构造子
private Sinleton(){};
//注意,这里没有final    
private static Sinleton instance = null;
//静态工厂方法 
public synchronized static Sinleton getSinleton(){
if(instance == null){
instance = new Sinleton();
}
return instance;
}

}


package com.mw.mbox.boss.demo;


/**
 * 饿汉式
 * @author niwei
 * //饿汉式单例类.在类初始化时,已经自行实例化 
 */
public class Sinleton2 {
//私有的默认构造方法
private Sinleton2(){}
//已经自行实例化 
private static Sinleton2 sinleton = new Sinleton2();
//静态工厂方法 
public static Sinleton2 getSinleton(){
return sinleton;
}
}


package com.mw.mbox.boss.demo;


import java.util.HashMap;
import java.util.Map;


//登记式单例类.
//类似Spring里面的方法,将类名注册,下次从里面直接获取。
public class Singleton3 {
    private static Map<String,Singleton3> map = new HashMap<String,Singleton3>();
    static{
        Singleton3 single = new Singleton3();
        map.put(single.getClass().getName(), single);
    }
    //保护的默认构造子
    protected Singleton3(){}
    //静态工厂方法,返还此类惟一的实例
    public static Singleton3 getInstance(String name) {
        if(name == null) {
            name = Singleton3.class.getName();
            System.out.println("name == null"+"--->name="+name);
        }
        if(map.get(name) == null) {
            try {
                map.put(name, (Singleton3) 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) {
        Singleton3 single3 = Singleton3.getInstance(null);
        System.out.println(single3.about());
    }
}



原创粉丝点击