& -JAVA based learning - Singleton

Singleton also called singleton pattern, refers to a class, in a JVM, only one instance exists.

 

Two single embodiment modes

Hungry man style is immediately loaded manner, regardless of whether the object will be used, will be loaded.
If the write performance of large consumption, accounting for longer time code, such as establishing a connection to the database in the constructor, then there will in time start feeling slightly Caton.

Lazy man's way is the delay in loading, only time will use to load. And there is thread-safe considerations (in view of the progress of the students to learn, to defer any thread sections do unfold).
Use lazy type, when activated, will feel slightly faster than a hungry man type, because do not object instantiation. But when the first call, it will instantiate operation, I feel a little slow.


Look business needs, if allowed to have more full time on business start-up and initialization, on the use of a hungry man type, otherwise use the lazy man

 

 

/ ** starving single embodiment mode * / 
public class GiantDragon {
// Constructors privatization that can not be instantiated by class new external
Private GiantDragon () {}
// Prepare a class attribute to an instance of object. Because class attribute, so only a
Private static GiantDragon new new instance GiantDragon = ();
// public static method, the caller is provided to get the object defined by the line 12
public static GiantDragon the getInstance () {
return instance;
}
}

/ ** lazy single embodiment mode * / 
public class GiantDragon2 {
// Constructors privatization that can not be instantiated by class new external
Private GiantDragon2 () {}
// Prepare a class attribute, for example a point object, but the point is temporarily null
Private static GiantDragon2 instance;
// public static method, returns an instance of an object
public static GiantDragon2 the getInstance () {
// first visit found not point to any object instance, when an object instance
IF (instance == null) {
instance GiantDragon2 new new = ();
}
// return object instance point
return instance;
}
}

Test // 
public static void main (String [] args) {
// new instantiation being given by
@ = GiantDragon giantDragon new GiantDragon ();

// get the object only by the getInstance
GiantDragon GiantDragon.getInstance G1 = ();
GiantDragon GiantDragon.getInstance = G2 ();
GiantDragon GiantDragon.getInstance G3 = ();

// same object
System.out.println (== G1 G2);
System.out.println (== G1 G3);
}


This is the time of the interview often examinations of points, face questions usually asked is this:
 
What is a singleton?
 
Answer time, to answer to the three elements
of privatization 1. Constructors
2. Static attribute point to an instance
getInstance 3. public static method returns the second step of the static properties
 

Guess you like

Origin www.cnblogs.com/leemlzm/p/12077901.html