GOF23 in Java (23 design mode)---------Singleton mode (Singleton)
In the Java this language, its advantage lies in its own portability above, and to be portable, it needs an intermediary as a translation work, in order to achieve local and Java unity, but in this case it is a considerable consumption of resources, so Java programmers need to constantly optimize their own code. The singleton pattern studied today is produced under these conditions,
The so-called Singleton pattern, there is only one instance, in the heap there is only one. If we have an example, we need one, but we will use it many times, and then there will be awkward problems.
Like what:
-
- The TaskManager (Task Manager) of Windows is typical of just one instance,
- Windows Recycle (Recycle Bin) in the system, the Recycle Bin only maintains one instance
- In our project, the class that reads the configuration file is often used,
- Website counters, generally also use a singleton mode, otherwise difficult to achieve synchronization
- Database connection pool design generally also uses singleton mode, because database connection is a kind of database resource
- Operating system's file system, because an operating system can have only one file system
- Application is also a singleton mode
- In spring, each bean is a singleton by default, and the advantage of this is that the spring container can manage
- In servlet programming, each servlet is also a singleton
- In spring mvc/struts 1, the control objects used are also single-instance
In the above we learned that the singleton pattern in our project, almost every day, so here, we study carefully, this design pattern of how to achieve the best (when it comes to implementation, it is realized that most of us only know there are two, while there are three patterns know not many people, and the use of deserialization, Reflection vulnerability to forced release of single case)
- a hungry man mode
- Lazy mode
- still use the static property to maintain the object's singleton mode, but in the method new out, when we go to adjust the method, then to load, is lazy, lazy to load, but because of the instantiation in the method, so we have to use the concept of the lock on the method to synchronize with him, if not lock, then we are in the a thread to remove the use of it and in the B thread to call it he is not a concept
- Pros: Can be delayed loading, and threads are safe
- Disadvantage: The method realizes the synchronization, so the utilization ratio of resources is low.
/*** Lazy Single case mode *@authorLiu Acid **/ Public classSluggard_singleton {Private StaticSluggard_singleton Singleton =NULL; PrivateSluggard_singleton () {} Public synchronized StaticSluggard_singleton newinstance () {if(Singleton = =NULL) {Singleton=NewSluggard_singleton (); } returnSingleton; }}
- Double-detector
- Place the code underneath the sync block inside the IF
- Problems: Due to compiler optimizations and other reasons, the JVM's underlying internal model is occasionally problematic and is not recommended for use.
/*** Double check lock for single case mode *@authorLiu Acid **/ Public classDoublecheck_singleton {Private StaticDoublecheck_singleton instance =NULL; Public StaticDoublecheck_singleton getinstance () {if(Instance = =NULL) {Doublecheck_singleton sc; synchronized(Doublecheck_singleton.class) {SC=instance; if(sc = =NULL) { synchronized(Doublecheck_singleton.class) { if(sc = =NULL) {SC=NewDoublecheck_singleton (); }} instance=SC; } } } returninstance; } PrivateDoublecheck_singleton () {}}
/*** Test static inner class implementation Singleton mode * This way: thread safety, high efficiency, and delay loading! * @authorLiu Acid **/ Public classstaticinnerclass{Private Static classstaticinnerclass{Private Static FinalStaticinnerclass instance =NewStaticinnerclass (); } PrivateStaticinnerclass () {}//method is not synchronized, the call efficiency is high! Public Staticstaticinnerclassgetinstance () {returnstaticinnerclass.instance; } }
- Enumeration implementation
/**@author*/publicenum enum_singleton{ // This enumeration element is itself a singleton! INSTANCE; // Add the actions you need! public void xxxxx () { } }
- How to prevent deserialization, reflection broken-loop Singleton mode (except enumeration)
- In reflection, if we call a private constructor, we throw an exception, but someone will skip the legal check so that it can access our private constructor.
ImportJava.lang.reflect.Constructor;/*** Test reflection and deserialization cracking Singleton mode *@authorLiu Acid **/ Public classmain{ Public Static voidMain (string[] args)throwsException {//invoking a private constructor directly by means of reflectionClass<singleton> clazz = (class<singleton>) class.forname ("Com.suansuan.singleton.Singleton"); Constructor<Singleton> C = Clazz.getdeclaredconstructor (NULL); //Skip a legal checkC.setaccessible (true); Singleton S1=c.newinstance (); Singleton S2=c.newinstance (); System.out.println (S1); SYSTEM.OUT.PRINTLN (S2);
}
}
-
- When deserializing, we also cannot get an object, so the following code solves both of these problems
/*** Test Lazy Singleton mode (how to prevent reflection and deserialization of the vulnerability) *@authorLiu Acid **/ Public classSingletonImplementsSerializable {//when the class is initialized, the object is not initialized (deferred loading, which is created when it is actually used). Private StaticSingleton instance; PrivateSingleton () {//Privatization Constructor//reflection, we do the following to circumvent, skip the legitimate detection of illegal access if(instance!=NULL){ Throw Newruntimeexception (); } } //method synchronization, the call efficiency is low! Public Static synchronizedSingleton getinstance () {if(instance==NULL) {instance=NewSingleton (); } returninstance; } //when deserializing, the object specified by this method is returned directly if Readresolve () is defined. You don't need to create new objects alone! PrivateObject Readresolve ()throwsobjectstreamexception {returninstance; } }
Summary: Use enumerations to replace a hungry man, use static inner classes instead of lazy-type
The first time to write a blog, thank you if you have the wrong room point, we progress together, common development, thank you
GOF23 in Java (23 design mode)---------Singleton mode (Singleton)