Single sample mode is completely analyzed (3) ---- Exploring simple but confused single case model

zhaozj2021-02-16  54

Using a registry using a single case certificate: You can register a single case of the class name in Example 8 at the running period specifying a single case class to prevent a plurality of single-size class classes. Class Registry: Example 8 Single-case IMPORT JAVA.UTIL.HASHMAP; Import Org.apache.log4j.logger; Public Class Singleton = LOGGER.PATION Static Logger Logger getRootLogger (); protected Singleton () {// Exists only to thwart instantiation} public static synchronized Singleton getInstance (String classname) {if (classname == null) throw new IllegalArgumentException ( "Illegal classname"); Singleton singleton = (Singleton) map.get (classname); if (singleton = null!) {logger.info ( "got singleton from map:" singleton); return singleton;} if (classname.equals ( "SingeltonSubclass_One")) singleton = new SingletonSubclass_One ( ); else IF ("SingereltonsubClass_TWO") Singleton = new singletonsubclass_two (); map.put (classname, singleton); logger.info ("Created Singleton: Singleton); Re Turn Singleton;} // Assume FunctionAlity Follows That's Attractive To Inherit} The base class of this code first creates an instance of a child class and stores them in a map. However, the base class has a high price because you have to replace its GetInstance () method for each subclass. Fortunately, we can use reflex to handle this problem. In a single case class reflection in the registry of Example 9, the reflection is used to instantiate a particular class object. With this implementation, the Singleton.GetInstance () method does not need to be rewritten in each of the subcates of the implemented.

Example 9 Example using reflection of singleton import java.util.HashMap; import org.apache.log4j.Logger; public class Singleton {private static HashMap map = new HashMap (); private static Logger logger = Logger.getRootLogger (); protected Singleton () {// Exists only to thwart instantiation} public static synchronized Singleton getInstance (String classname) {Singleton singleton = (Singleton) map.get (classname); if (! singleton = null) {logger.info ( "got singleton from map: " singleton); return singleton;} try {singleton = (Singleton) Class.forName (classname) .newInstance ();} catch (ClassNotFoundException cnf) {logger.fatal (" Could not find class " classname);} catch (InstantiationException ie) {logger.fatal ( "Could not instantiate an object of type" classname);} catch (IllegalAccessException ia) {logger.fatal ( "Could not access class" classname); } map.put (classname, singleton); Logger.info ("Created Singleton); Return Singleton;} The registry of the single-case class should be described: they should be encapsulated in their own classes to maximize multiplexing. Package Registration Table Example 10 lists a single case registry.

Example 10 a SingletonRegistry class import java.util.HashMap; import org.apache.log4j.Logger; public class SingletonRegistry {public static SingletonRegistry REGISTRY = new SingletonRegistry (); private static HashMap map = new HashMap (); private static Logger logger = Logger.getRootLogger (); protected SingletonRegistry () {// Exists to defeat instantiation} public static synchronized Object getInstance (String classname) {Object singleton = map.get (classname); if (singleton = null!) {return singleton;} try {singleton = Class.forName (classname) .newInstance (); logger.info ( "created singleton:" singleton);} catch (ClassNotFoundException cnf) {logger.fatal ( "Could not find class" classname); } catCH ("" COULDN '@Stantiate An Object of Type " ClassName);} catch (illegalaccessException} {logger.fatal (" COULDN) 'T Access Class " ClassName);} map.put (classname, singleton); return singleton;} Note I is implemented as a single sample mode. I also use this registry so that it can store and retrieve any type of object. Example 11 The Singleton class was used using this registry. Example 11 uses a package registry Singleton class import java.util.HashMap; import org.apache.log4j.Logger; public class Singleton {protected Singleton () {// Exists only to thwart instantiation} public static Singleton getInstance. () {Return (Singleton) SingletonRegistry.registry.getInstance (ClassName);}} The Singleton class is used to obtain a single case object by the unique instance of that registry. Now we already know how to implement a single case class for thread security and how to use a registry to specify a single-case class name in the running period, then let us examine how to arrange type of loader and processing serialization.

ClassLoaders In many cases, using multiple class loaders is very common - including servlet containers - so don't matter how careful when you implement your single case class, you can eventually get multiple single-size instances . If you want to make sure that your single case class is only loaded with the same class loader, you must specify this class loader; for example: private static class getclass (string classname) throws ClassNotFoundException {ClassLoader ClassLoader = Thread.currentThread () getContextClassLoader ();. if (classLoader == null) classLoader = Singleton.class.getClassLoader (); return (classLoader.loadClass (classname));}} this method attempts to the current thread that class The loader is associated; if ClassLoader is NULL, this method uses the class loader that is loaded with a single-class class class. This method can be replaced with class.Forname (). Serialization If you serialize a single case class, then refacture it twice, then you will get the two instances of the single-class class unless you implement the readresolve () method, like this: Example 12 A serialized the singleton class import org.apache.log4j.Logger; public class singleton implements java.io.Serializable {public static singleton INSTANCE = new singleton (); protected singleton () {// Exists only to thwart instantiation} private Object readResolve. () {Return Instance;}} The above single-case implementation returns a unique instance from the ReadResolve () method; this will only return the same single case instance regardless of when the Singleton class is reconstructed.

Example 13 Tested a single example of Example 12: Example 13 Test a sequentially sequenceful single-size IMPORT JAVA.IO. *; Import org.apache.log4j.logger; import junit.framework.assert; import junit.framework. TestCase; public class SingletonTest extends TestCase {private Singleton sone = null, stwo = null; private static Logger logger = Logger.getRootLogger (); public SingletonTest (String name) {super (name);} public void setUp () {sone = Singleton.INSTANCE; stwo = Singleton.INSTANCE;} public void testSerialize () {logger.info ( "testing singleton serialization ..."); [b] writeSingleton (); Singleton s1 = readSingleton (); Singleton s2 = readSingleton ( ); Assert.assertEquals (true, s1 == s2); [/ b]} private void writeSingleton () {try {FileOutputStream fos = new FileOutputStream ( "serializedSingleton"); ObjectOutputStream oos = new ObjectOutputStream (fos); Singleton s = Singleton.instance; Oos.WriteObject (Singleton.instance); oos.flush ();} catch (NotSerializa BleException se) {logger.fatal ("not serializable exception:" se.getMessage ());} catch (ioException IOX) {Logger.FATAL ("IO Exception:" Iox.getMessage ());}} readSingleton () {Singleton s = null; try {FileInputStream fis = new FileInputStream ( "serializedSingleton"); ObjectInputStream ois = new ObjectInputStream (fis); s = (Singleton) ois.readObject ();} catch (ClassNotFoundException cnf) {logger .fatal ("Class Not Found Exception:" CNF.getMessage ());

转载请注明原文地址:https://www.9cbs.com/read-22561.html

New Post(0)