JAVA_ singleton design pattern

Singleton design pattern refers to: implement a class in memory, there is only one object design pattern. Chinese-style divided hungry and lazy man's mode:

Want a project at runtime, a class only a unique object in memory, then, to ensure that:

First, other classes can not create the object constructor -------------------------- The object belongs to the class of private modification (can not in other classes inside this create a class object)                                         

Secondly, the object to be accessed by other classes, you can create only one of the objects in the object belongs to a class -------------------------- private static definition of a class in the present modified class object

Finally, it must provide access methods in this class there, so that other classes can access ---------------------------------- public static ---- define a modification in the class, the class-based return value type method reference

1. starving design mode:

class singleColumn{

private singleColumn(){}

private static singleColumn targetObject = new singleColumn();

public static singleColumn requestMethod (){

return targetObject;

}

}

class mainClass{

public static void main(String[] args){

singleColumn targetObject = singleColumn.requestMethod();

}

}

 

2. lazy design mode:

class singleColumn{

private singleColumn(){}

private static singleColumn targetObject = null;

public static singleColumn requestMethod (){

targetObject = new singleColumn();

return targetObject;

}

}

class mainClass{

public static void main(String[] args){

singleColumn targetObject = singleColumn.requestMethod();

}

}

 

Hungry and lazy style of Han difference is: the former is when the class initialization of static objects to complete the construction of the building which is called when the access method to complete.

 

It is recommended to use a hungry man type. Because the lazy man might be clogged.

 

 

 

Guess you like

Origin www.cnblogs.com/A-PP-Z-droplet/p/11871515.html