Java的登記式單例代碼

網上很多關於登記式單例的代碼,有的是錯誤的,有的過於繁雜,因此自己寫了一個代碼例子,供大家參考。
參考了並補全了https://github.com/simple-android-framework-exchange/android_design_patterns_analysis/tree/master/singleton/mr.simple
中的內容。

package com.dumaisoft.singleton;

import java.util.HashMap;

/**
 * @author wxb
 * Description:登記式單例,將需要單例的類都登記在一個Manager中,需要時調取
 *          在Android系統中,我們經常會通過Context獲取系統級別的服務,比如WindowsManagerService, 
 *          ActivityManagerService等,更常用的是一個叫LayoutInflater的類。這些服務會在合適的時候以單例的形式註冊在系統中,
 *          在我們需要的時候就通過Context的getSystemService(String name)獲取。
 *          這些服務就是使用了登記式單例的模式。
 *
 * 2016-1-24
 * 下午9:33:21
 */
public class TestSingleton5 {

    public static void main(String[] args) {
        Singleton_1 s1 = (Singleton_1) SingletonManager.getSingleton(Singleton_1.class.getName());
        s1.doSomething();

        Singleton_2 s2 = (Singleton_2) SingletonManager.getSingleton(Singleton_2.class.getName());
        s2.doSomething();

        Singleton_3 s3 = (Singleton_3) SingletonManager.getSingleton(Singleton_3.class.getName());
        s3.doSomething();
    }
}


class SingletonManager {
    private final static HashMap<String, Object> map = new HashMap<String, Object>();

    //在靜態域中直接註冊本系統所需的所有單例類
    static {
        registeSingleton(Singleton_1.class.getName(),new Singleton_1());
        registeSingleton(Singleton_2.class.getName(),new Singleton_2());
        registeSingleton(Singleton_3.class.getName(),new Singleton_3());
    }
    public static void registeSingleton(String name, Object singleton) {
        if (!map.containsKey(name)) {
            map.put(name, singleton);
        }
    }

    public static void unregisteSingleton(String name) {
        if (map.containsKey(name)) {
            map.remove(name);
        }
    }

    public static Object getSingleton(String name) {
        if (map.containsKey(name)) {
            return map.get(name);
        } else {
            return null;
        }
    }
}

class Singleton_1 {
    public void doSomething() {
        System.out.println(this.getClass().getName() + " do sth.");
    }
}

class Singleton_2 {
    public void doSomething() {
        System.out.println(this.getClass().getName() + " do sth.");
    }
}

class Singleton_3 {
    public void doSomething() {
        System.out.println(this.getClass().getName() + " do sth.");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章