使用注册表
使用一个单例类注册表可以:
在运行期指定单例类
防止产生多个单例类子类的实例
在例8的单例类中,保持了一个通过类名进行注册的单例类注册表:
例8带注册表的单例类
- importjava.util.HashMap;
- importorg.apache.log4j.Logger;
- publicclassSingleton{
- privatestaticHashMapmap=newHashMap();
- privatestaticLoggerlogger=Logger.getRootLogger();
- protectedSingleton(){
- //Existsonlytothwartinstantiation
- }
- publicstaticsynchronizedSingletongetInstance(Stringclassname){
- if(classname==null)thrownewIllegalArgumentException("Illegalclassname");
- Singletonsingleton=(Singleton)map.get(classname);
- if(singleton!=null){
- logger.info("gotsingletonfrommap:"+singleton);
- returnsingleton;
- }
- if(classname.equals("SingeltonSubclass_One"))
- singleton=newSingletonSubclass_One();
- elseif(classname.equals("SingeltonSubclass_Two"))
- singleton=newSingletonSubclass_Two();
- map.put(classname,singleton);
- logger.info("createdsingleton:"+singleton);
- returnsingleton;
- }
- //Assumefunctionalityfollowsthat'sattractivetoinherit
- }
这段代码的基类首先创建出子类的实例,然后把它们存储在一个Map中。但是基类却得付出很高的代价因为你必须为每一个子类替换它的getInstance()方法。幸运的是我们可以使用反射处理这个问题。
使用反射
在例9的带注册表的单例类中,使用反射来实例化一个特殊的类的对象。与例8相对的是通过这种实现,Singleton.getInstance()方法不需要在每个被实现的子类中重写了。
例9使用反射实例化单例类
- importjava.util.HashMap;
- importorg.apache.log4j.Logger;
- publicclassSingleton{
- privatestaticHashMapmap=newHashMap();
- privatestaticLoggerlogger=Logger.getRootLogger();
- protectedSingleton(){
- //Existsonlytothwartinstantiation
- }
- publicstaticsynchronizedSingletongetInstance(Stringclassname){
- Singletonsingleton=(Singleton)map.get(classname);
- if(singleton!=null){
- logger.info("gotsingletonfrommap:"+singleton);
- returnsingleton;
- }
- try{
- singleton=(Singleton)Class.forName(classname).newInstance();
- }
- catch(ClassNotFoundExceptioncnf){
- logger.fatal("Couldn'tfindclass"+classname);
- }
- catch(InstantiationExceptionie){
- logger.fatal("Couldn'tinstantiateanobjectoftype"+classname);
- }
- catch(IllegalAccessExceptionia){
- logger.fatal("Couldn'taccessclass"+classname);
- }
- map.put(classname,singleton);
- logger.info("createdsingleton:"+singleton);
- returnsingleton;
- }
- }
关于单例类的注册表应该说明的是:它们应该被封装在它们自己的类中以便最大限度的进行复用。
封装注册表
例10列出了一个单例注册表类。
例10一个SingletonRegistry类
- importjava.util.HashMap;
- importorg.apache.log4j.Logger;
- publicclassSingletonRegistry{
- publicstaticSingletonRegistryREGISTRY=newSingletonRegistry();
- privatestaticHashMapmap=newHashMap();
- privatestaticLoggerlogger=Logger.getRootLogger();
- protectedSingletonRegistry(){
- //Existstodefeatinstantiation
- }
- publicstaticsynchronizedObjectgetInstance(Stringclassname){
- Objectsingleton=map.get(classname);
- if(singleton!=null){
- returnsingleton;
- }
- try{
- singleton=Class.forName(classname).newInstance();
- logger.info("createdsingleton:"+singleton);
- }
- catch(ClassNotFoundExceptioncnf){
- logger.fatal("Couldn'tfindclass"+classname);
- }
- catch(InstantiationExceptionie){
- logger.fatal("Couldn'tinstantiateanobjectoftype"+
- classname);
- }
- catch(IllegalAccessExceptionia){
- logger.fatal("Couldn'taccessclass"+classname);
- }
- map.put(classname,singleton);
- returnsingleton;
- }
- }
注意我是把SingletonRegistry类作为一个单例模式实现的。我也通用化了这个注册表以便它能存储和取回任何类型的对象。例11显示了的Singleton类使用了这个注册表。
例11使用了一个封装的注册表的Singleton类
- importjava.util.HashMap;
- importorg.apache.log4j.Logger;
- publicclassSingleton{
- protectedSingleton(){
- //Existsonlytothwartinstantiation.
- }
- publicstaticSingletongetInstance(){
- return(Singleton)SingletonRegistry.REGISTRY.getInstance(classname);
- }
- }
上面的Singleton类使用那个注册表的唯一实例通过类名取得单例对象。
现在我们已经知道如何实现线程安全的单例类和如何使用一个注册表去在运行期指定单例类名,接着让我们考查一下如何安排类载入器和处理序列化。
Classloaders
在许多情况下,使用多个类载入器是很普通的--包括servlet容器--所以不管你在实现你的单例类时是多么小心你都最终可以得到多个单例类的实例。如果你想要确保你的单例类只被同一个的类载入器装入,那你就必须自己指定这个类载入器;例如:
- privatestaticClassgetClass(Stringclassname)
- throwsClassNotFoundException{
- ClassLoaderclassLoader=Thread.currentThread().getContextClassLoader();
- if(classLoader==null)
- classLoader=Singleton.class.getClassLoader();
- return(classLoader.loadClass(classname));
- }
- }
这个方法会尝试把当前的线程与那个类载入器相关联;如果classloader为null,这个方法会使用与装入单例类基类的那个类载入器。这个方法可以用Class.forName()代替。
序列化
如果你序列化一个单例类,然后两次重构它,那么你就会得到那个单例类的两个实例,除非你实现readResolve()方法,像下面这样:
例12一个可序列化的单例类
- importorg.apache.log4j.Logger;
- publicclassSingletonimplementsjava.io.Serializable{
- publicstaticSingletonINSTANCE=newSingleton();
- protectedSingleton(){
- //Existsonlytothwartinstantiation.
- }
- [b]privateObjectreadResolve(){
- returnINSTANCE;
- }[/b]}
上面的单例类实现从readResolve()方法中返回一个唯一的实例;这样无论Singleton类何时被重构,它都只会返回那个相同的单例类实例。
例13测试了例12的单例类:
例13测试一个可序列化的单例类
- importjava.io.*;
- importorg.apache.log4j.Logger;
- importjunit.framework.Assert;
- importjunit.framework.TestCase;
- publicclassSingletonTestextendsTestCase{
- privateSingletonsone=null,stwo=null;
- privatestaticLoggerlogger=Logger.getRootLogger();
- publicSingletonTest(Stringname){
- super(name);
- }
- publicvoidsetUp(){
- sone=Singleton.INSTANCE;
- stwo=Singleton.INSTANCE;
- }
- publicvoidtestSerialize(){
- logger.info("testingsingletonserialization...");
- [b]writeSingleton();
- Singletons1=readSingleton();
- Singletons2=readSingleton();
- Assert.assertEquals(true,s1==s2);[/b]}
- privatevoidwriteSingleton(){
- try{
- FileOutputStreamfos=newFileOutputStream("serializedSingleton");
- ObjectOutputStreamoos=newObjectOutputStream(fos);
- Singletons=Singleton.INSTANCE;
- oos.writeObject(Singleton.INSTANCE);
- oos.flush();
- }
- catch(NotSerializableExceptionse){
- logger.fatal("NotSerializableException:"+se.getMessage());
- }
- catch(IOExceptioniox){
- logger.fatal("IOException:"+iox.getMessage());
- }
- }
- privateSingletonreadSingleton(){
- Singletons=null;
- try{
- FileInputStreamfis=newFileInputStream("serializedSingleton");
- ObjectInputStreamois=newObjectInputStream(fis);
- s=(Singleton)ois.readObject();
- }
- catch(ClassNotFoundExceptioncnf){
- logger.fatal("ClassNotFoundException:"+cnf.getMessage());
- }
- catch(NotSerializableExceptionse){
- logger.fatal("NotSerializableException:"+se.getMessage());
- }
- catch(IOExceptioniox){
- logger.fatal("IOException:"+iox.getMessage());
- }
- returns;
- }
- publicvoidtestUnique(){
- logger.info("testingsingletonuniqueness...");
- Singletonanother=newSingleton();
- logger.info("checkingsingletonsforequality");
- Assert.assertEquals(true,sone==stwo);
- }
- }
前面这个测试案例序列化例12中的单例类,并且两次重构它。然后这个测试案例检查看是否被重构的单例类实例是同一个对象。下面是测试案例的输出:
- Buildfile:build.xml
- init:
- [echo]Build20030422(22-04-200311:32)
- compile:
- run-test-text:
- [java].INFOmain:testingsingletonserialization...
- [java].INFOmain:testingsingletonuniqueness...
- [java]INFOmain:checkingsingletonsforequality
- [java]Time:0.1
- [java]OK(2tests)
单例模式结束语
单例模式简单却容易让人迷惑,特别是对于Java的开发者来说。在这篇文章中,作者演示了Java开发者在顾及多线程、类载入器和序列化情况如何实现单例模式。作者也展示了你怎样才能实现一个单例类的注册表,以便能够在运行期指定单例类。
本文详细介绍了Java中实现单例模式的方法,包括线程安全、类加载器处理、序列化等关键问题,并提供了单例注册表的具体实现。

被折叠的 条评论
为什么被折叠?



