A single example mode in Java _java

Source: Internet
Author: User

Single-Example pattern concept:

The single case pattern in Java is a common design pattern, the single example mode is divided into three kinds: the lazy type single case, the A Hungry man type single case, the registration type single example three kinds.

A single case pattern has some features:

1, Singleton class can only have one instance.

2. A singleton class must create its own unique instance itself.

3. A singleton class must provide this instance to all other objects.

The singleton pattern ensures that a class has only one instance and instantiates it itself and supplies the instance to the entire system. In computer systems, the driver objects of thread pools, caches, log objects, dialog boxes, printers, and graphics cards are often designed as single examples. These applications have more or less the functionality of the resource manager. Each computer can have several printers, but only one printer Spooler to prevent two print jobs from being exported to the printer at the same time. Each computer can have several communication ports, and the system should centrally manage these communication ports to avoid a single communication port being invoked simultaneously by two requests. In short, the choice of single case mode is to avoid inconsistent state, to avoid the administration of the Bulls.

First, look at a classic single example implementation.

public class Singleton {
  private static Singleton uniqueinstance = null;
 
  Private Singleton () {
    //Exists only to defeat instantiation.
  }
 
  public static Singleton getinstance () {
    if (uniqueinstance = null) {
      uniqueinstance = new Singleton ();
    } return
    uniqueinstance;
  }
  Other methods ...
}

Singleton by restricting the construction method to private, the class is instantiated externally, and within the same virtual machine scope, the only instance of Singleton can be accessed through the getinstance () method. (In fact, the Java reflection mechanism is able to instantiate a class with a constructed method private, which essentially invalidates all Java Singleton implementations.) This question is not discussed here, but the reflection mechanism does not exist. )

However, the above implementation does not consider thread safety issues. Thread safety means that if you have more than one thread running in the process of your code, those threads may run the code at the same time. If the result of each run is the same as that of a single-threaded operation, and the value of other variables is the same as expected, it is thread-safe. Or, a class or program provides an interface that is atomic to a thread or a switch between multiple threads does not cause ambiguity in the execution of the interface, which means that we do not have to consider the problem of synchronization. Obviously the above implementation does not meet the requirements of thread safety, and multiple singleton instances are likely to occur in concurrent environments.

 public class Teststream {private String name;
   Public String GetName () {return name;
   public void SetName (String name) {this.name = name; The class can have only one instance private Teststream () {}//Private parameterless constructor//The class must be created by itself//There are 2 ways/*private static final Teststream ts=n
   EW Teststream (); * * private static Teststream ts1=null;
     This class must automatically supply this instance object to the entire system public static Teststream Gettest () {if (ts1==null) {ts1=new teststream ();
   return ts1;
   public void GetInfo () {System.out.println (' output message ' +name); }
 }
 public class Testmain {public
   static void Main (String [] args) {
     teststream s=teststream.gettest ();
     S.setname ("Zhang Xiaoxiang:");
    System.out.println (S.getname ());
     Teststream s1=teststream.gettest ();
     S1.setname ("Zhang Xiaoxiang:");
     System.out.println (S1.getname ());
     S.getinfo ();
     S1.getinfo ();
     if (s==s1) {
       System.out.println ("created with the same instance");
    } else if (s!=s1) {
       System.out.println ("created not the same instance");
     } else{
       System.out.println ("Application Error");}}
 

Run Result:

Zhang Xiaoxiang:
Zhang Xiaoxiang:
Output Message Zhang Xiaoxiang:
Output Message Zhang Xiaoxiang:
Create the same instance

Conclusion: The result shows that the singleton pattern provides an object-only access point for an object-oriented application, regardless of the functionality it implements, and the entire application shares an instance object.

1. A hungry man type single case class

A hungry man Singleton class. The
   default constructor
   private Singleton1 () {}
   ///has 
   been instantiated by itself when class initialization is already instantiated by the public class Singleton1 {//private Private static final Singleton1 single = new Singleton1 ();
   Static Factory method Public 
   static Singleton1 getinstance () {return single
     ;
   }
 }

2. Lazy type Single Case class

 Lazy single Instance class. Instantiate the public 
 class Singleton2 {
   //private default constructor
   private Singleton2 () {}
   /note, at the first call There is no final  
   private static Singleton2 single=null;
   Static Factory method public 
   synchronized static Singleton2 getinstance () {
     if (single = = null) {Single 
       = new Singleton 2 ();
     } 
    return single;
   }
 

3. Registration type Single Case class

 Import Java.util.HashMap;
 Import Java.util.Map;
 A single instance of the registration class.
 Like spring inside the method, the class name registration, the next time from the inside directly to get.
   public class Singleton3 {private static map<string,singleton3> Map = new hashmap<string,singleton3> ();
     static{Singleton3 single = new Singleton3 ();
   Map.put (Single.getclass (). GetName (), single);
     }//protected default constructor protected Singleton3 () {}//static Factory method, return the unique instance of this class public static Singleton3 getinstance (String name) {
       if (name = = null) {name = Singleton3.class.getName ();
     System.out.println ("name = = NULL" + "--->name=" +name);
       } if (Map.get (name) = = null) {try {map.put (name, Singleton3) class.forname (name) newinstance ());
       catch (Instantiationexception e) {e.printstacktrace ();
       catch (Illegalaccessexception e) {e.printstacktrace ();
       catch (ClassNotFoundException e) {e.printstacktrace ();
   } return Map.get (name); }//A schematic business method public StrinG About () {return "Hello, I am Regsingleton."
    public static void Main (string[] args) {Singleton3 single3 = singleton3.getinstance (null);
   System.out.println (Single3.about ());
 }
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.