"Java design mode" 1. Singleton mode

Source: Internet
Author: User
Tags instance method zend framework

Write in front

There are 23 types of Java design patterns, although I don't count them carefully. Singleton mode, as if it is necessary in common Java projects, such as rice is absolutely indispensable to rice, no problem. Here's your understanding, broadly divided into several areas:

1. When you need to use a singleton mode, that is, a single-instance mode of using the scene, talk about the concept of singleton mode

2. What kinds of singleton patterns are common?

3. Advantages of Singleton mode

4. Single-case patterns and thread-safe stuff

1.0 When do I need a singleton mode 1.1 definition

Singleton mode, which is a design pattern for creating objects, ensures that one of its classes has only one instance, that is, it ensures that the entire class has only one instantiation method that can be called by the outside world and is automatically instantiated for the entire Java Project (System) class invocation.

This class: Singleton class.

1.2 Usage scenarios for single-case mode

Here Baidu: Configuration information classes, management classes, control classes, façade classes, proxy classes are usually designed as singleton classes. Like the struts, spring framework of Java. NET Spring.net framework, and PHP's Zend Framework are heavily used in singleton mode.

A configuration information class code is posted here, which is the global configuration file used in my project.

Resourceloader.java, this class is a singleton for reading the configuration file
1  PackageFriends.util.common;2 3 ImportJava.io.File;4 ImportJava.io.FileInputStream;5 ImportJava.util.HashMap;6 ImportJava.util.Map;7 Importjava.util.Properties;8 9 /**Ten * Created by Samuel on 2017/5/2. One  * A * Singleton mod (lazy-type) -  * -  */ the  Public classResourceloader { -  -     Private StaticResourceloader Loader; -     Private Staticmap<string, properties> loadermap =NewHashmap<string, properties>(); +  -     PrivateResourceloader () { +     } A  at      Public StaticResourceloader getinstance () { -         if(loader==NULL) -Loader =NewResourceloader (); -  -         returnloader; -     } in  -      PublicProperties getpropfromproperties (String fileName)throwsException { to  +Properties prop =Loadermap.get (fileName); -         if(Prop! =NULL) { the             returnprop; *         } $String FilePath =NULL;Panax NotoginsengString Configpath = System.getproperty ("Configurepath"); -  the         if(Configpath = =NULL) { +  A             //load the root directory of the classes theStringBuffer Root_path =NewStringBuffer ( This. GetClass (). getClassLoader (). GetResource ("/"). GetPath ()); +  -             //Our configuration file is placed under the Conf of the classes's sibling directory, so $FilePath = Root_path.append (".. /conf/"). Append (FileName). toString (); $  -}Else { -FilePath = Configpath + "/" +FileName; the         } -Prop =NewProperties ();WuyiProp.load (NewFileInputStream (NewFile (FilePath )); the  - Loadermap.put (fileName, prop); Wu         returnprop; -     } About}
View Code
Propertiesutil.java
 PackageFriends.util.common;Importjava.util.Properties;ImportJava.util.concurrent.ConcurrentHashMap;ImportJava.util.concurrent.ConcurrentMap;/*** Created by Samuel on 2017/5/2.*/ Public classPropertiesutil {Private StaticResourceloader loader =resourceloader.getinstance (); //k-v in the storage configuration file    Private Staticconcurrentmap<string, string> configmap =NewConcurrenthashmap<string, string>(); Private Static FinalString default_config_file = "Wxset.properties"; Private StaticProperties prop =NULL;  Public Staticstring Getstringbykey (String key, String propname) {Try{prop=loader.getpropfromproperties (propname); } Catch(Exception e) {Throw NewRuntimeException (e); } Key=Key.trim (); if(!Configmap.containskey (Key)) {            if(Prop.getproperty (key)! =NULL) {configmap.put (key, Prop.getproperty (key)); }        }        returnConfigmap.get (key); }     Public Staticstring Getstringbykey (String key) {returnGetstringbykey (key, Default_config_file); }     Public StaticProperties getProperties () {Try {            returnloader.getpropfromproperties (Default_config_file); } Catch(Exception e) {e.printstacktrace (); return NULL; }    }}
Constant.java
1  PackageFriends.util.common;2 3 /**4 * Created by Samuel on 2017/5/2.5  *6 * Configuration of global constants7  */8  Public classConstant {9 Ten     /** One * the AppID A      */ -      Public Static FinalString appid_wx = Propertiesutil.getstringbykey ("AppID"); -  the  -}

In summary, want to invoke, some parameters in the configuration file, in the constant are defined, the direct call can.

Other scenes I can not demonstrate, may have encountered many, but did not notice (despise oneself 100 times), perhaps did not come across, OK, say to the subject oneself kan ...

2. What kinds of singleton patterns are common?

There are 23 Java design patterns, and the implementation of the singleton mode although not so much, but also a lot, before read a post, talked about 7 kinds of, point here

Here, click on theeffective Java mentioned Enum enumeration way to implement the singleton mode, here I will talk about the usual lazy-type (lazy-type) and a hungry man-type

2.1 Lazy Type

The so-called lazy type, is very lazy, you do not respond to me, I do not work, in the final analysis is unconscious. Code such as the Resourceloader.java in the loader in advance just declare, and no instantiation, call the instantiation Method getinstance () to determine whether the instantiation of the situation to instantiate, this is the typical lazy, why is lazy is not idle ghost, Lazy, a word: "International practice"!

2.2-A Hungry man

Compared to the lazy, it is naturally a hungry ghost, a home, do not urge it, see the delicious food on the eat, I change the Resourceloader.java, paste, we compare, we know what called a hungry ghost, the amount, a hungry man

Resourceloader2.java
1  PackageFriends.util.common;2 3 /**4 * Created by Samuel on 2017/5/2.5  *6 * Singleton mod a hungry man style7  *8  */9  Public classResourceLoader2 {Ten  One     /** A * Affirm the privatization of static instances, only for instance method calls -      */ -     Private StaticResourceLoader2 loader =NewResourceLoader2 (); the  -     /** - * As with the lazy type, privatization constructs the method, does not let other class call -      */ +     PrivateResourceLoader2 () { -     } +  A      Public StaticResourceLoader2 getinstance () { at         returnloader; -     } -  -  -}
View Code

The loader in Resourceloader2.java is instantiated directly (too hungry) when the project is started, and the instance is directly obtained when invoking the instantiation Method getinstance ().

3. Advantages of Singleton mode

1, control the use of resources, through thread synchronization to control the concurrent access to resources

2, the production of control cases, in order to achieve the purpose of saving resources

3, control the sharing of data, in the condition of not establishing a direct association, let a number of unrelated processes or threads to achieve communication between

These three points from Brother Siang summary, the latter two points I think it should be obvious, as for the 1th, look at the following decomposition

4. Single-case patterns and thread-safe stuff

4.1 Lazy-type, is thread unsafe, multi-threaded case is fatal,

4.2 Some people say that in the implementation method getinstance () plus keyword synchronized is not thread-safe? Yes, with that, it's too inefficient.

4.3 A hungry man mode, is thread-safe, this approach based on the classloder mechanism to avoid multi-threaded synchronization problems, but no lazy loading effect

Here are the notes below; I've read a blog post and talked about 7 of them, and this post talks about the 2 pits of the singleton pattern, which I think is important.

1. If a singleton is loaded by a different class loader, there may be instances of multiple singleton classes. It is assumed that not remote access, such as some servlet containers, use a completely different class loader for each servlet, so that if there are two Servlets accessing a singleton class, they will have their own instance.

2. If the singleton implements the Java.io.Serializable interface, then instances of this class may be serialized and restored. In any case, if you serialize an object of a singleton class and then restore multiple objects, you will have multiple instances of the Singleton class.

The fix for the first problem is:

1 Private StaticClass getclass (String classname)2                                          throwsClassNotFoundException {3ClassLoader ClassLoader =Thread.CurrentThread (). Getcontextclassloader (); 4     5       if(ClassLoader = =NULL)   6ClassLoader = Singleton.class. getClassLoader (); 7     8       return(Classloader.loadclass (classname)); 9    }   Ten}

The fix for the second problem is:

1  Public classSingletonImplementsjava.io.Serializable {2     Public StaticSingleton INSTANCE =NewSingleton (); 3     4    protectedSingleton () {5       6    }   7    PrivateObject readresolve () {8             returnINSTANCE; 9       }  Ten}
At last

And shamelessly picked the fruit, fools, study together, to the great God a gift!

"Java design mode" 1. Singleton mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.