Single-instance mode singleton (three-created) for design patterns

Source: Internet
Author: User

1. What is a single-case mode?

  Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the entire system .

The singleton mode has the following characteristics:
    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 all other objects.

The singleton mode is mainly divided into: a hungry man mode, lazy mode.

A hungry man and lazy-type differences:

From the name, a hungry man and lazy, a hungry man is the class once loaded, the singleton initialization to complete, to ensure that the getinstance, the singleton is already exist, and the idle lazy, only when the call getinstance, Just go back and initialize the singleton.

The singleton pattern focuses on a thread-safe issue.

What is thread safety?

If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe.

Or, the interface provided by a class or program is atomic to the thread, or the switch between multiple threads does not result in ambiguity in the execution of the interface, that is, we do not have to consider the problem of synchronization, which is thread-safe.

2. Single-case mode application scenario

1. Task Manager for Windows is a very typical singleton mode (this is familiar), think about it, can you open two Windows Task Manager? Don't believe you try it yourself oh ~

2. Windows Recycle Bin (Recycle Bin) is also a typical single-instance application. During the whole system operation, the Recycle Bin maintains the only one instance.

3. The website counter, generally also uses the Singleton pattern realization, otherwise difficult to synchronize.

4. Application of the log application, the general use of single-case mode implementation, which is generally due to the shared log file is open, because there can only be one instance to operate, otherwise the content is not good to append.

5. The Web application's configuration object reads, generally also applies the singleton pattern, this is because the configuration file is the shared resource.

6. Database connection pooling is generally designed with a singleton pattern, because database connections are a database resource. Database software system in the use of database connection pool, mainly to save the open or close the database connection caused by the efficiency of loss, this loss of efficiency is very expensive, because how to use a single case mode to maintain, can greatly reduce this loss.

7. Multithreaded thread pools are generally designed with a singleton pattern, because thread pooling is convenient for controlling the threads in the pool.

8. Operating system file system, is also a large example of the implementation of the singleton mode, an operating system can only have one file system

3. Example of a single application.

The main implementations and explanations are written in the code.

/*** @FileName singleton.java* @Package com.ali.pattern.singleton* @Description * <p> Here are some of the key words involved here: * A variable is declared volatile, which means that the variable is modified at any time by other threads, so it cannot be cache in the thread memory. Volatile is a variable modifier, while synchronized acts on a code or method. * Volatile only synchronizes the value of a variable between the thread memory and the "primary" memory, while synchronized synchronizes the values of all variables by locking and unlocking a monitor. * Obviously synchronized consumes more resources than volatile. * Depending on the context of the program, the Java keyword final has "This cannot be changed" or "final State" meaning, it can be modified non-abstract class, non-abstract class member methods and variables.        You may need to stop the change in two ways: design or efficiency.        The final class cannot be inherited, there are no subclasses, and the methods in the final class are final by default.        The final method cannot be overridden by a method of a class, but can be inherited.        The final member variable represents a constant, which can only be assigned once, and the value will no longer change after the value is assigned.        Final cannot be used to modify a construction method.   Note: The private member method of the parent class is not overridden by the class method, so the private type method defaults to the final type.        Static represents the meaning of "global" or "static", which modifies member variables and member methods, and can also form statically static blocks of code, but there is no concept of global variables in the Java language. member variables and member methods that are modified by static are independent of any object of the class. That is, it does not depend on class-specific instances and is shared by all instances of the class.        As long as this class is loaded, the Java virtual machine can find them within the method area of the runtime data area based on the class name.        Therefore, a static object can be accessed before any of its objects are created, without referencing any objects. Static member variables and member methods that are decorated with public are essentially global variables and global methods, and when declaring the object city of its class, do not generate a copy of the static variable, but all instances of the class share the same static variable. </p>* @Author Ali Blog:Http://www.cnblogs.com/accipiter* @Date January 19, 2016 afternoon 1:21:46* @Version V1.0.1*/ PackageCom.ali.pattern.singleton;/*** @ClassName Singleton * <p> But the above-mentioned lazy singleton implementation does not take into account thread safety issues, it is thread insecure </p> * @Description TODO * @Date pm 1:21:46 */ Public classSingleton {//a hungry man    Private StaticSingleton Sigleton1 =NewSingleton (); /*** @Title Getinstancee * @Description a hungry man mode, which is thread-safe in itself. * @return* @Return Singleton * @Throws * @user Administrator * @Date January 19, 2016*/     Public StaticSingleton Getinstancee () {returnSigleton1; }    //Lazy    Private StaticSingleton singleton=NULL; PrivateSingleton () {}/*** @Title getinstance * @Description Thread insecure *@return* @Return Singleton * @Throws * @user Administrator * @Date January 19, 2016*/     Public StaticSingleton getinstance () {if(NULL==Singleton) {Singleton=NewSingleton (); }        returnSingleton; }    /*** @Title getinstancesafe * @Description thread safety, every time to synchronize, will affect performance, after all, 99% of the case is not required to synchronize, *@return* @Return Singleton * @Throws * @user Administrator * @Date January 19, 2016*/     Public Static synchronizedSingleton Getinstancesafe () {if(NULL==Singleton) {Singleton=NewSingleton (); }        returnSingleton; }    /*** @Title getinstancesafed * @Description Double Lock * Ensures that synchronization is done only for the first invocation of the Singleton, which is also thread-safe, while avoiding the performance loss of synchronization every time * * @return* @Return Singleton * @Throws * @user Administrator * @Date January 19, 2016*/     Public StaticSingleton getinstancesafed () {if(NULL==Singleton) {            synchronized(Singleton.class) {                if(NULL==Singleton) {Singleton=NewSingleton (); }                }            }        returnSingleton; }    /*** @ClassName Lazyholder * @Description static internal classes for both thread safety and the performance impact of synchronization * @Date pm 1:44:53*/    Private Static classlazyholder{Private Static FinalSingleton singleton=NewSingleton (); }     Public Static FinalSingleton Getinstanceclass () {returnLazyholder.singleton; }         Public voidOperateinti) {System.out.println (i+ ", Operation! "); }    /*** @Title Main * @Description TODO *@paramargs * @Return void * @Throws * @user Administrator * @Date January 19, 2016*/     Public Static voidMain (string[] args) {singleton.getinstance (). Operate (1); Singleton.getinstancesafe (). Operate (2); Singleton.getinstancesafed (). Operate (3); Singleton.getinstanceclass (). Operate (4); Singleton.getinstancee (). Operate (5); }}

Single-instance mode singleton (three-created) for design patterns

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.