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.");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值