EXAMPLE single mode (super detail)

Contents:
definition of a single-mode embodiment of the
implementation steps two single mode described embodiments and the advantages and disadvantages + code for
defining a singleton of
mathematics and logic in, singleton defined as "", "one and only one set of elements" .
JAVA singleton pattern definition: a class and only one example, and examples of their own available to the entire system.
JAVA object singletons: such an object to be the only instance in the system.
Code for two points of
1. Only one instance of a class
2. it must create an instance of itself
3. he must provide the entire system in this example
implementation:
1. lazy formula (Recommended double locking) ------ the most basic implementation of the thread context singleton
/ **

  • Double lock lazy man: objects need to be created if the use, both to save memory space and can guarantee thread safety
  • Cons: However, because of the sort of chaos executive function jvm, occasionally there will be thread safe
  • Solution: You can read in the memory by adding the word volitatle

* /
Public class Singleton1 {
Private volatile static instance Singleton1 = null;
Private Singleton1 () {} // declare the private constructor is not created in order to ensure that by way of new
public static Singleton1 the getInstance () {
IF (instancenull) {
synchronized(Singleton1.class) {
if(instance
null) {
instance=new Singleton1();
}
}
}
return instance;

}
}

When starving formula 2. Create class loader -----
public class the Singleton {
private static Singleton Final the Singleton the Singleton = new (); //
// declare the private constructor is to ensure not to create new objects by way of
private singleton () {}

public Singleton getInstance() {
return singleton;

}
}

3. An enumerated (highly recommended)
**

  • Advantages: Code simple way to achieve optimum singleton
  • Cons: the sequence problem (before and after a sequence of two unequal objects)

/
Public enum {Singleton2
INSTANCE;
public void Method () {}
}
4. static inner class
/
*

  • Static inner class advantages: no need to load the class immediately inside the external load, it does not take up memory
  • The only resistance while this method can be achieved not only a thread but also to ensure safety of a single embodiment may also delay the instantiation of the singleton

*/
public class Singleton3 {
public static class SingletonHolder{
private static final Singleton3 instance=new Singleton3();
private SingletonHolder() {}
public static Singleton3 getInstance() {
return SingletonHolder.instance;
}
}
}

Published 10 original articles · won praise 3 · Views 575

Guess you like

Origin blog.csdn.net/qq_43614498/article/details/104899755
Recommended