Before in the development of the old use of some design patterns but it is not very understand, so hard to ponder over the heart. Here's what I've figured out and I hope it works for you. If you find a problem, please help me correct it.
What is a singleton mode?
The initial definition of the singleton pattern appears in design mode: "Guarantees that a class has only one instance, and provides a global access point to access it." ”
The singleton schema definition in Java; "A class has and has only one instance, and it instantiates itself to provide the instance to the entire system." ”
Second, why use a single case mode?
For some classes in the system, only one instance is important. For example, there can be multiple print tasks in a system, but only one task is working; a system has only one window manager or file system; A system can have only one timing tool or ID generator. You can only open one task Manager in Windows OS. If you do not use the mechanism to make a Window object unique, you will pop up multiple windows, if they display exactly the same content, then duplicate the object, wasting memory resources, if the contents of these windows are inconsistent, it means that a moment system has multiple states, and the actual discrepancy, will also cause misunderstanding for users, I don't know which one is the real state. So sometimes it is important to ensure that the uniqueness of an object in the system is that a class can have only one instance.
How do you ensure that there is only one instance of a class and that this instance is easy to access? Defining a global variable ensures that an object can be accessed at any time, but it does not prevent us from instantiating multiple objects. A better solution is to have the class itself responsible for preserving its only instance. This class guarantees that no other instance is created, and it can provide a way to access the instance. This is the pattern motive of the singleton pattern.
Three, the characteristics of single-case mode
There are three characteristics of the singleton mode
1, the Singleton class can have only one instance.
2, the Singleton class must create its own unique instance.
3. The Singleton class must provide this instance to other objects (the system as a whole).
From the point of view of concrete implementation, one is that the class of Singleton mode only provides private constructor, and the second is that the class definition contains a static private static object of the class, and the third is that the class provides a static public The function is used to create or get a static private object of its own.
Iv. several common patterns of single cases in Java
Do you have a general idea of the singleton pattern through the above introduction? No, then continue to enlarge your strokes.
Based on the characteristics of the singleton pattern, a singleton object is usually used as a carrier for the configuration information in the program (think of the application in Android often doing some configuration initialization in it), because it ensures that other objects read consistent information. For example, in a server program, the configuration information for the server may be stored in a database or file, which is read uniformly by a single object, and other objects in the service process can access the singleton object if they want to obtain the configuration information. This approach greatly simplifies configuration management in complex environments, especially in multi-threaded environments, but it can also lead to some synchronization problems as the application scenario differs.
1. A hungry man type single case
//饿汉式单例类.在类初始化时,已经自行实例化 publicclass Singleton { //私有的默认构造子 privateSingleton() {} //已经自行实例化 privatestaticnew Singleton(); //静态工厂方法 publicstaticgetInstance() { return single; } }
In the example above, when the class is loaded, the static variable single is initialized, and the private constructor of the class is called. The only instance of the Singleton class is then constructed.
A hungry man type is actually a kind of comparative image appellation. Since hungry, then in the creation of object instances is more anxious, hungry, so in the loading class when the object instance is created
privatestaticfinalnew Singleton();
A hungry man-type is a typical space change time, when the class is loaded will create an instance of the class, whether you use it, first created, and then each time you call, there is no need to judge, save the running time.
2, lazy-type single case
//lazy Singleton class. Instantiate yourself when you first call public class Singleton { Private singleton () {} private static Singleton single=null ; //static Factory method public static synchronized Singleton getinstance () { if (single = null ) {single = new Singleton (); } return single; } }
In the above lazy singleton class implementation, the static factory method is synchronized to handle multi-threaded environments.
The lazy type is actually a kind of comparative image appellation. Now that you're lazy, you don't have to worry about creating an object instance. Will wait until immediately to use the object instance will be created, lazy people, always can not shirk the time to really do the work, so when loading the object does not create an object instance.
privatestatic Singleton single=null;
Lazy-type is a typical time to change space , that is, every time you get an instance will be judged to see if you need to create an instance, wasting judgment time. Of course, if no one ever uses it, it doesn't create an instance, saving memory space
Because the lazy implementation is thread-safe, this reduces the speed of the entire visit and is judged every time. So is there a better way to achieve it?
3. Double check plus lock
You can achieve thread safety by using double check and lock, and you can make performance unaffected.
Double check Lock: Not every time into the getinstance () need to synchronize, but first out of sync, enter the method, first check whether a singleton object exists, if not exist before the following synchronization block, this is the first check, enter the synchronization block, check again if the instance exists, if not exist, Create an instance (Singleton object) in the case of synchronization, which is the second check. This only needs to be synchronized once, thus reducing the time wasted in the synchronization of multiple judgments.
The implementation of the double check lock mechanism uses the keyword volatile, which means that the value of a volatile variable is not cached by the local thread, and that all read and write to the variable is directly operating shared memory, ensuring that the variable is handled correctly by multiple threads. It's not clear what volatile is looking for. Volatile analysis
code example:
Public classSingleton {Private volatile StaticSingleton instance =NULL;Private Singleton(){} Public StaticSingletongetinstance(){//Check if the instance exists and enter the following sync block if it does not exist if(Instance = =NULL){//synchronization block, thread-safe creation instanceSynchronized (Singleton.class) {//Check to see if the instance exists and create the instance if it does not exist if(Instance = =NULL) {instance =NewSingleton (); } } }returnInstance }}
This approach enables thread-safe creation of instances without much impact on performance. It is just the first time to create an instance of synchronization, the future does not need synchronization, thereby speeding up the speed of operation.
tip: Because the volatile keyword may block out some of the necessary code optimizations in a virtual machine, it is not very efficient to run. It is therefore generally recommended that no special needs be used. In other words, although you can use the double check and lock mechanism to implement a thread-safe singleton, it is not recommended to be used extensively, depending on the situation.
According to the above analysis, the two common single-instance implementations have a small flaw, then there is a scheme, both to achieve lazy loading, but also to achieve thread safety? That's the next way to zoom in, then yo.
4. Static internal class
Public class Singleton { Private Singleton(){}/** * Class-level internal class, that is, a static member-style inner class, an instance of the inner class has no binding relationship to an instance of an external class, and is loaded only when it is called, enabling lazy loading. */ Private Static class singletonholder{ /** * Static initializer, guaranteed by the JVM for thread safety * / Private StaticSingleton instance =NewSingleton (); } Public StaticSingletongetinstance(){returnSingletonholder.instance; }}
When the GetInstance method is called for the first time, It first reads singletonholder.instance, causing the Singletonholder class to be initialized, and when the class is loaded and initialized, it initializes its static domain to create an instance of singleton, because it is a static domain, so only when the virtual machine loads the class Initialized once and is guaranteed to be thread-safe by a virtual machine.
5. Singleton and enumeration
publicenum Singleton { /** * 定义一个枚举的元素,它就代表了Singleton的一个实例。 */ uniqueInstance; /** * 单例可以有自己的操作 */ publicvoidsingletonOperation(){ //功能处理 }}
As described in "Efficient Java Second Edition", the single-element enumeration type has become the best way to implement Singleton. It is very simple to use enumerations to implement a singleton, just to write an enumeration type that contains a single element.
For me, I prefer the first and the fourth way, easy to understand. It also implements thread safety at the JVM layer (if not multiple classloader environments). In general, I'll use the first way, only if you want to explicitly implement the lazy loading effect, the fourth way
V. Typical single-case mode in Android Application Class 1, what is application?
Application, like Activity,service, is a system component of the Android framework that creates a application object to store some information about the system when the Android program starts. Usually we do not need to specify a application, then the system will automatically help us to create, if you need to create their own application, it is easy to create a class to inherit application and register in manifest application tag (just add a name attribute to the application tag to set the name of your application).
The Android system creates an object of the application class for each program runtime and creates only one, so application can be said to be a singleton (singleton) A class of patterns. And the life cycle of the Application object is the longest in the whole program, and its life cycle is equal to the life cycle of the program. Because it is a global singleton, the objects obtained in different activity,service are the same object. So through the application to do some, data transfer, data sharing, such as data caching operations.
2, skillfully use the characteristics of a single case model, through the application to transfer data
If there is an activity a, jump to activity B, and need to recommend some data, it is usually intent.putextra () let intent carry, or have a bundle to add information to the bundle so intent recommend bundle object To implement delivery. However, one problem with this is that the data types that intent and bundles can carry are basic data types that are cumbersome to implement for complex data transfer, and often require the implementation of serializable or parcellable interfaces. This is actually an IPC data transfer method for Android. If the two of our activity is in the same process, why bother, just pass the reference to the object that needs to pass through.
The basic idea is this. Create a HashMap in application, with the string as index, and object as value so that our HashMap can store any type of object. In activity A, you put the object that needs to be passed in the HashMap, and then pass the index string to activity B through intent or other passes, and activity B can take the object out of the HashMap based on the string. As long as the downward turn of the type, the implementation of the object's delivery.
Vi. Summary
After crawling through the web, I finally learned what a singleton mode is, thanks here
Http://www.cnblogs.com/java-my-life/archive/2012/03/31/2425631.html
http://blog.csdn.net/songylwq/article/details/6058771
Http://www.blogjava.net/kenzhh/archive/2013/03/15/357824.html
Http://www.cnblogs.com/hxsyl/archive/2013/03/19/2969489.html
http://blog.csdn.net/pi9nc/article/details/11200969
Java design Patterns in single-instance mode and important use in Android