单例模式完全剖析(3)---- 探究简单却又使人迷惑的单例模式

单例模式完全剖析(3)---- 探究简单却又使人迷惑的单例模式
kevin 翻译   更新:2003-11-06 20:07:45  版本: 1.0   

使用注册表


使用一个单例类注册表可以:
  • 在运行期指定单例类

  • 防止产生多个单例类子类的实例

  • 在例8的单例类中,保持了一个通过类名进行注册的单例类注册表:
    例8 带注册表的单例类
    1. import java.util.HashMap;
    2. import org.apache.log4j.Logger;
    3. public class Singleton {
    4.    private static HashMap map = new HashMap();
    5.    private static Logger logger = Logger.getRootLogger();
    6.    protected Singleton() {
    7.       // Exists only to thwart instantiation
    8.    }
    9.    public static synchronized Singleton getInstance(String classname) {
    10.       if(classname == nullthrow new IllegalArgumentException("Illegal classname");
    11.          Singleton singleton = (Singleton)map.get(classname);
    12.       if(singleton != null) {
    13.          logger.info("got singleton from map: " + singleton);
    14.          return singleton;
    15.       }
    16.       if(classname.equals("SingeltonSubclass_One"))
    17.             singleton = new SingletonSubclass_One();         
    18.          else if(classname.equals("SingeltonSubclass_Two"))
    19.             singleton = new SingletonSubclass_Two();
    20.       map.put(classname, singleton);
    21.       logger.info("created singleton: " + singleton);
    22.       return singleton;
    23.    }
    24.    // Assume functionality follows that's attractive to inherit
    25. }

    这段代码的基类首先创建出子类的实例,然后把它们存储在一个Map中。但是基类却得付出很高的代价因为你必须为每一个子类替换它的getInstance()方法。幸运的是我们可以使用反射处理这个问题。

    使用反射


    在例9的带注册表的单例类中,使用反射来实例化一个特殊的类的对象。与例8相对的是通过这种实现,Singleton.getInstance()方法不需要在每个被实现的子类中重写了。
    例9 使用反射实例化单例类
    1. import java.util.HashMap;
    2. import org.apache.log4j.Logger;
    3. public class Singleton {
    4.    private static HashMap map = new HashMap();
    5.    private static Logger logger = Logger.getRootLogger();
    6.    protected Singleton() {
    7.       // Exists only to thwart instantiation
    8.    }
    9.    public static synchronized Singleton getInstance(String classname) {
    10.       Singleton singleton = (Singleton)map.get(classname);
    11.       if(singleton != null) {
    12.          logger.info("got singleton from map: " + singleton);
    13.          return singleton;
    14.       }
    15.       try {
    16.          singleton = (Singleton)Class.forName(classname).newInstance();
    17.       }
    18.       catch(ClassNotFoundException cnf) {
    19.          logger.fatal("Couldn't find class " + classname);    
    20.       }
    21.       catch(InstantiationException ie) {
    22.          logger.fatal("Couldn't instantiate an object of type " + classname);    
    23.       }
    24.       catch(IllegalAccessException ia) {
    25.          logger.fatal("Couldn't access class " + classname);    
    26.       }
    27.       map.put(classname, singleton);
    28.       logger.info("created singleton: " + singleton);
    29.       return singleton;
    30.    }
    31. }


    关于单例类的注册表应该说明的是:它们应该被封装在它们自己的类中以便最大限度的进行复用。

    封装注册表


    例10列出了一个单例注册表类。
    例10 一个SingletonRegistry类
    1. import java.util.HashMap;
    2. import org.apache.log4j.Logger;
    3. public class SingletonRegistry {
    4.    public static SingletonRegistry REGISTRY = new SingletonRegistry();
    5.    private static HashMap map = new HashMap();
    6.    private static Logger logger = Logger.getRootLogger();
    7.    protected SingletonRegistry() {
    8.       // Exists to defeat instantiation
    9.    }
    10.    public static synchronized Object getInstance(String classname) {
    11.       Object singleton = map.get(classname);
    12.       if(singleton != null) {
    13.          return singleton;
    14.       }
    15.       try {
    16.          singleton = Class.forName(classname).newInstance();
    17.          logger.info("created singleton: " + singleton);
    18.       }
    19.       catch(ClassNotFoundException cnf) {
    20.          logger.fatal("Couldn't find class " + classname);    
    21.       }
    22.       catch(InstantiationException ie) {
    23.          logger.fatal("Couldn't instantiate an object of type " + 
    24.                        classname);    
    25.       }
    26.       catch(IllegalAccessException ia) {
    27.          logger.fatal("Couldn't access class " + classname);    
    28.       }
    29.       map.put(classname, singleton);
    30.       return singleton;
    31.    }
    32. }

    注意我是把SingletonRegistry类作为一个单例模式实现的。我也通用化了这个注册表以便它能存储和取回任何类型的对象。例11显示了的Singleton类使用了这个注册表。
    例11 使用了一个封装的注册表的Singleton类
    1. import java.util.HashMap;
    2. import org.apache.log4j.Logger;
    3. public class Singleton {
    4.    protected Singleton() {
    5.       // Exists only to thwart instantiation.
    6.    }
    7.    public static Singleton getInstance() {
    8.       return (Singleton)SingletonRegistry.REGISTRY.getInstance(classname);
    9.    }
    10. }

    上面的Singleton类使用那个注册表的唯一实例通过类名取得单例对象。
    现在我们已经知道如何实现线程安全的单例类和如何使用一个注册表去在运行期指定单例类名,接着让我们考查一下如何安排类载入器和处理序列化。

    Classloaders


    在许多情况下,使用多个类载入器是很普通的--包括servlet容器--所以不管你在实现你的单例类时是多么小心你都最终可以得到多个单例类的实例。如果你想要确保你的单例类只被同一个的类载入器装入,那你就必须自己指定这个类载入器;例如:
    1. private static Class getClass(String classname) 
    2.                                          throws ClassNotFoundException {
    3.       ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    4.       if(classLoader == null)
    5.          classLoader = Singleton.class.getClassLoader();
    6.       return (classLoader.loadClass(classname));
    7.    }
    8. }

    这个方法会尝试把当前的线程与那个类载入器相关联;如果classloader为null,这个方法会使用与装入单例类基类的那个类载入器。这个方法可以用Class.forName()代替。

    序列化


    如果你序列化一个单例类,然后两次重构它,那么你就会得到那个单例类的两个实例,除非你实现readResolve()方法,像下面这样:
    例12 一个可序列化的单例类
    1. import org.apache.log4j.Logger;
    2. public class Singleton implements java.io.Serializable {
    3.    public static Singleton INSTANCE = new Singleton();
    4.    protected Singleton() {
    5.       // Exists only to thwart instantiation.
    6.    }
    7. [b]      private Object readResolve() {
    8.             return INSTANCE;
    9.       }[/b]}

    上面的单例类实现从readResolve()方法中返回一个唯一的实例;这样无论Singleton类何时被重构,它都只会返回那个相同的单例类实例。
    例13测试了例12的单例类:
    例13 测试一个可序列化的单例类
    1. import java.io.*;
    2. import org.apache.log4j.Logger;
    3. import junit.framework.Assert;
    4. import junit.framework.TestCase;
    5. public class SingletonTest extends TestCase {
    6.    private Singleton sone = null, stwo = null;
    7.    private static Logger logger = Logger.getRootLogger();
    8.    public SingletonTest(String name) {
    9.       super(name);
    10.    }
    11.    public void setUp() {
    12.       sone = Singleton.INSTANCE;
    13.       stwo = Singleton.INSTANCE;
    14.    }
    15.    public void testSerialize() {
    16.       logger.info("testing singleton serialization...");
    17. [b]      writeSingleton();
    18.       Singleton s1 = readSingleton();
    19.       Singleton s2 = readSingleton();
    20.       Assert.assertEquals(true, s1 == s2);[/b]   }
    21.    private void writeSingleton() {
    22.       try {
    23.          FileOutputStream fos = new FileOutputStream("serializedSingleton");
    24.          ObjectOutputStream oos = new ObjectOutputStream(fos);
    25.          Singleton s = Singleton.INSTANCE;
    26.          oos.writeObject(Singleton.INSTANCE);
    27.          oos.flush();
    28.       }
    29.       catch(NotSerializableException se) {
    30.          logger.fatal("Not Serializable Exception: " + se.getMessage());
    31.       }
    32.       catch(IOException iox) {
    33.          logger.fatal("IO Exception: " + iox.getMessage());
    34.       }
    35.    }
    36.    private Singleton readSingleton() {
    37.       Singleton s = null;
    38.       try {
    39.          FileInputStream fis = new FileInputStream("serializedSingleton");
    40.          ObjectInputStream ois = new ObjectInputStream(fis);
    41.          s = (Singleton)ois.readObject();
    42.       }
    43.       catch(ClassNotFoundException cnf) {
    44.          logger.fatal("Class Not Found Exception: " + cnf.getMessage());
    45.       }
    46.       catch(NotSerializableException se) {
    47.          logger.fatal("Not Serializable Exception: " + se.getMessage());
    48.       }
    49.       catch(IOException iox) {
    50.          logger.fatal("IO Exception: " + iox.getMessage());
    51.       }
    52.       return s;
    53.    }
    54.    public void testUnique() {
    55.       logger.info("testing singleton uniqueness...");
    56.       Singleton another = new Singleton();
    57.       logger.info("checking singletons for equality");
    58.       Assert.assertEquals(true, sone == stwo);
    59.    }
    60. }

    前面这个测试案例序列化例12中的单例类,并且两次重构它。然后这个测试案例检查看是否被重构的单例类实例是同一个对象。下面是测试案例的输出:
    1. Buildfile: build.xml
    2. init:
    3.      [echo] Build 20030422 (22-04-2003 11:32)
    4. compile:
    5. run-test-text:
    6.      [java] .INFO main: testing singleton serialization...
    7.      [java] .INFO main: testing singleton uniqueness...
    8.      [java] INFO main: checking singletons for equality
    9.      [java] Time: 0.1
    10.      [java] OK (2 tests)
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值