Java Project (5) -- Application and Research of Singleton Mode
The Singleton mode is a very unique mode. Few people compare it with other modes, because the singleton mode is very simple and special, and its role is to ensure that a class has a unique instance, and make a global variable accessible. the method to ensure that this class is instantiated only once is to convert the constructor into private, except that it itself cannot create a new object, and then write the instantiation process in the public method of the class itself, whether the new object is determined by its own judgment. If an instance already exists, the existing object is directly returned. If the new object does not exist, a new instance is returned. when other classes want to instantiate an object, call this public method.
Hungry Chinese (pre-initialized object)
// Hungry Class XmlConfigReader {private static XmlConfigReader instance = new XmlConfigReader (); private XmlConfigReader () {} public static XmlConfigReader getInstance () {return instance ;}}Lazy (delayed initialization object)
// Lazy Class XmlConfigReader {private static XmlConfigReader instance = null; public static synchronized XmlConfigReader getInstance () {if (instance = null) {instance = new XmlConfigReader ();} return instance ;}}
We often hear the concept of "Double-Check Locking", that is, "Double Lock", because there is also a Locking method, that is, using Lock.
Class XmlConfigReader{ private static XmlConfigReader instance;private static readonly object syncRoot=new object();private XmlConfigReader(){}public static XmlConfigReader getInstance(){ if(instance==null){Lock( syncRoot) { if(instance==null){instance=new XmlConfigReader();}}}return instance;}}
Comparison:
The Singleton mode can be divided into two categories. This static initialization method is instantiated when the class is loaded. It occupies system resources in advance compared with the first instantiation when the class is referenced; however, the lazy style requires locking to ensure the security of multi-thread access, but the hungry style does not. we have to use it for good...
Singleton application in the project:
In DRP, almost every module has a Manager. In the early stage of system development, because only ClientManager is available, the singleton mode is as follows:
public class ClientManager {private static ClientManager instance=new ClientManager();private ClientManager(){}public static ClientManager getInstance(){return instance;}}
As the complexity of the system increases, more and more managers are emerging, such as ItemManager and FlowCardManager. At this time, managers and Dao are separated and layered. the system uses the abstract factory + reflection technology to instantiate the Manager class and Dao class. the Singleton is applied in the factory again.
public class BeanFactory {private static BeanFactory instance=new BeanFactory();private final String beansConfigFile="beans-config.xml";private Document doc;private BeanFactory(){try {doc=new SAXReader().read(Thread.currentThread().getContextClassLoader().getResourceAsStream(beansConfigFile));} catch (DocumentException e) {e.printStackTrace();throw new RuntimeException();}}public static BeanFactory getInstance(){return instance;}}
The following code is part of the implementation of the Manager Singleton in the factory class. at first, I thought it was the metadata sharing mode. Later I found that this implementation was more flexible than the metadata sharing mode. it can ensure that the object has only one instance, so it is still a singleton mode application. the more things we will use later, the more we will not just be confined to a certain model or technology. We will enjoy the yuan, Singleton, factory, proxy ......
// Save the private Map serviceMap = new HashMap () object related to the Service (); /*** get the service product series according to the product number * @ param beanId * @ return */public synchronized Object getServiceObject (Class c) {// If an instance of the relevant Object exists, returns if (serviceMap. containsKey (c. getName () {return serviceMap. get (c. getName ();} Element beanElt = (Element) doc. selectSingleNode ("// service [@ id = \" "+ c. getName () + "\"] "); String className = beanElt. attributeValue ("class"); Object service = null; try {service = Class. forName (className ). newInstance (); // place the created object in the map serviceMap. put (c. getName (), service);} catch (Exception e) {throw new RuntimeException ();} return service ;}
Through the above analysis and application, let's look at the focus of the singleton mode:
In implementation, Private Static member variables, private constructor methods, and public static methods solve the problem of global access and instantiation control.
A Singleton does not mean creation, but access. That is to say, if the object to be accessed or called does not exist, create one. This is the only one and cannot be created later; if this object exists, the object is returned. Although the attributes of this object have been changed countless times because of the re-assignment, the object is unique but not static.