1. Single case design mode (singleton)
Examples of use: When using the same configuration information object for multiple programs, such as using singleton mode when connecting to a database, only one connection is taken out at a time
Step: ① privatize the constructor for this class
② privatization of a static object
③ public A static method that returns the Created object
Lazy Style Templates:
/**@author */Publicclass Singleton { Private Singleton () { } privatestaticnew Singleton (); Public Static Singleton getinstance () { return Singleton; }}
A hungry man-style templates:
/*** A hungry man: lazy initialization of this singleton instance, to consider multi-threaded simultaneous request initialization problem * Delay initialization reason: ① static initialization, there is not enough information to initialize the singleton *② and get resources, such as database connection, especially in a particular session, it package When the object instance is not required by the containing application **/ Public classSingletonofhungry {Private StaticObject Classlock = singletonofhungry.class;
Privatesingletonofhungry () {}Private StaticSingletonofhungry singletonofhungry =NULL; Public Staticsingletonofhungry getinstance () {synchronized(Classlock) {//syncif(Singletonofhungry = =NULL) {singletonofhungry=Newsingletonofhungry (); } returnsingletonofhungry; } }}
A Hungry Man type Demo:
/*** Uninitialized a Hungry man single-case factory*/ Public classFactory {Private Longnum; Private StaticObject Classlock = Factory.class; PrivateFactory () {num= 0; } Private StaticFactory Factory; Public StaticFactory getfactory () {synchronized(classlock) {if(factory==NULL) {Factory=NewFactory (); } returnFactory; } } Public voidRecordnum () {synchronized(classlock) {num++; } }}
Getting an instance can also be written like this:
Public Static Factory getfactory () { if(factory==null) { //cannot be locked after instantiation Synchronized (classlock) { if (factory==null) { //prevents locking, is instantiated by another thread and does not need to instantiate new Factory () ; }}} return factory; }
Design Patterns Mode