A single example mode of design mode--singleton

Source: Internet
Author: User

A Single example mode of design mode --singleton

Design intent:

the Guaranteed class has only one instance and can be used globally by the application. To ensure this, it is necessary for this class to create its own object and to have a public calling method . also, the other class cannot instantiate it, so the construction method is set to private.

key points of the singleton model  

One is that a class can have only one instance;

The second is that it must create this instance on its own;

Thirdly, it must provide this instance to the whole system on its own.

For example:

have a"single-instance objects", while"Client Armor","Customer B" and the"Customer C"is the three customer object for a singleton object. As you can see, all of the customer objects share a single Singleton object. And from the singleton to its own connection line, it can be seen that the Singleton object holds a reference to itself. Some resource managers are often designed as singleton patterns. In a computer system, resources that need to be managed include software external resources, such as a number of printers per computer, but only onePrinter SpoolerTo prevent both print jobs from being output to the printer at the same time. Each computer can have several fax cards, but there should only be one software that manages the fax card to avoid the case of two fax jobs being uploaded to the fax card at the same time. Each computer can have several communication ports, and the system should centrally manage these communication ports to prevent a communication port from being called simultaneously by two requests.

Method of implementation:

There are many types of singleton patterns, and here are some ways to use the Singleton pattern:
The "A Hungry Man mode" a hungry man method is to create an object instance when the class is first referenced, regardless of whether it is actually required to be created.

 Public   classsingleton{Private Static FinalSingleton Singleton =NewSingleton (); /*** Private Constructors*/    PrivateSingleton () {}/*** Get examples *@return     */     Public StaticSingleton getinstance () {returnSingleton; }     Public Static voidsay () {System.out.println ("Singleton mode created! "); }}
 Public class Main {    publicstaticvoid  main (string[] args) {        main m=New  Main ();        Singleton.getinstance (). Say ();    }}

The benefit of this is that writing is simple, but it is not possible to delay the creation of objects. But most of the time we want the object to delay loading as much as possible to reduce the load, so we need the following lazy method:

"Lazy Way"

This approach allows for delayed loading, but there is a fatal weakness: thread insecurity. If you have two threads that call the Getsingleton () method at the same time, there is a great chance that the object will be created repeatedly.

 Public class Singleton {    privatestaticnull;     Private Singleton () {}      Public Static Singleton Getsingleton () {        ifnullnew  Singleton ();         return Singleton;}    }

Three ways to troubleshoot thread insecurity:

1, on the GetInstance method plus synchronization

 Public Static synchronized Singleton getinstance () {           ifnull) {                 new  Singleton ();           }             return Single ;  

2. Double check Lock

Synchronized (Singleton.class), which is equivalent to a lock on the Singleton object, any thread can run first if the lock is reached, until it is possible for the lock to be executed by the other thread.
 Public Static Singleton getinstance () {          ifnull) {                synchronized (Singleton.  Class                   ){ifnull) {                      new  Singleton ();                  }                }            }             return Singleton;       }  

 

3. Static internal class

 Public classSingleton {Private Static classLazyholder {Private Static FinalSingleton INSTANCE =NewSingleton (); }        PrivateSingleton () {} Public Static FinalSingleton getinstance () {returnlazyholder.instance; }    }    

thinking: the difference between a singleton pattern and a static class (a class, all methods are static methods) in Java

Because both singleton and static classes have good accessibility, there are many similarities between them, for example, they can be used directly without creating objects, and they can be submitted to unique instances, which appear to be used for the same task at a very high height.

1. When should I use a singleton mode in Java, and when should I use a static class?

If your singleton does not need to maintain any state, only provides a method of global access, this scenario considers using static classes, and static methods are faster than singleton because static bindings are performed at compile time.      Keep in mind, however, that it is not recommended to maintain state information in static classes, especially in concurrent environments, which can cause bad race conditions if there are no appropriate synchronization measures to modify multithreading concurrency. If you need to put some tool methods together, you can choose to use static methods, but other things that require singleton access to resources should use Singleton mode. the difference between a single case (a realizable Class) and a static class (presentation method) in 2.Java1) Static analogy Singleton has better performance because static methods are bound at compile time. 2) Again, their difference is the ability to override, because the static method in Java is not covered, which leads to too much flexibility in its wood, and on the other hand, you can override the methods defined in the Singleton class in a way that inherits. 3) Static class is difficult to simulate, so it is difficult to single test, single case easier to simulate, because it is also easier than static classes to write unit tests, regardless of God horse single-case God horse, you can pass simulation objects, such as construction methods or method parameters. 4) If you need to maintain state information in your needs, the singleton is more appropriate than a static class, because the latter is very scary in maintaining state information and leads to a slippery bug. 5) If it is a very heavy object, the singleton can be lazy loading, but the static class has no such advantage, and very eager to load. 6) Many frameworks that rely on injection have good management of the singleton, such as spring, which is very easy to use. 3.Java, the advantages of selecting a singleton rather than a static classThe primary advantage of single and Static is that the former is more object-oriented than the latter, and using singleton can extend the base class through inheritance and polymorphism, realize interface and more ability to provide different implementations, if we discuss Java.lang.Runtime, in Java it is a singleton, call GetRuntime () method, which returns different implementations based on different JVMs, but also guarantees that there is an instance in each JVM, and that if Java.lang.Runtime is a static class, it is unlikely that different implementations will be returned by different JVMs. This is the difference between a singleton and a static class in Java, and when you need a fully capable object, choose Singleton, and if you just pre-sell some static methods, use static classes.

 

A single example mode of design mode--singleton

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.