Starting with the introduction of the next single mode, which is the singleton mode, we are mainly different from the prototype pattern in spring, the singleton mode is to ensure that a class exists only one instance, is only initialized once, after the first completion of initialization, reuse, the return is this instance , And it's not a new one, it's common in the DAO layer, we define a factory class (seesionfactory), not every time we go to new, the advantage is that it saves memory and time, but if the value of the attribute inside your object has changed, it's not appropriate to use a singleton. Can only be re-new, our general usage the action layer of spring is the use of this prototype, you can create multiple instances. Need to say, although the use of single example saves memory and time, but in multi-threaded concurrency scenario is easy to thread security issues , there is an article can be learned under: http://blog.csdn.net/liushuijinger/article/ details/9069801, write down the common factory class gets the single-state code template for manipulating database object instances:
Import Javax.persistence.entitymanagerfactory;import Javax.persistence.persistence;public Final class EMF {private Final static entitymanagerfactory emfinstance= persistence.createentitymanagerfactory ("Hbase-filesharesys");p ublic Static synchronized Entitymanagerfactory getinstance () { return emfinstance;}}
The above template uses JPA to get the database operand through persistence.createentitymanagerfactory ("Persistence file Location"). In fact, reading the above article, I found that this method is not the safest, the following in addition to the more complete single-state mode code:
Inner class implements lazy public class Singleton { private static class singletonholder{ //singleton variable private static Singleton Instance = new Singleton (); } The method of structuring the privatization ensures that the outer class cannot be instantiated by the constructor. Private Singleton () { } //Get Singleton object instance public static Singleton getinstance () { System.out.println ( "I am an internal class singleton!" "); return singletonholder.instance;} }
Lazy (avoid the waste of resources above), thread-safe, simple code. Because the Java mechanism specifies that the inner class Singletonholder be loaded (and lazy) only when the getinstance () method is first called, and that the loading process is thread-safe (thread-safe). An instance is instantiated once when the inner class is loaded.
Using the single State (Singleton) mode to get the database operation object