The difference between a hungry man and lazy-type
- 1, a hungry man type is space change time, lazy type is time change space
- 2, in multi-threaded access, a hungry man does not create multiple objects, while lazy-type may create multiple objects
- Lazy mode
class Singleton {//1,私有构造方法,其他类不能访问该构造方法了private Singleton(){}//2,声明一个引用private static Singleton s ;//3,对外提供公共的访问方法public static Singleton getInstance() { //获取实例if(s == null) { //线程1等待,线程2等待 s = new Singleton();}return s;}
# 饿汉模式
Class Singleton {
1, private constructor method, other classes cannot access the constructor.
Private Singleton () {}
2, create this class object
private static Singleton s = new Singleton ();
3, provide public access to external methods
public static Singleton getinstance () {//Get instance
return s;
}
# 第三种:
Class Singleton1 {
1, private constructor method, other classes cannot access the constructor.
Private Singleton1 () {}
2, declare a reference
public static final Singleton1 s = new Singleton1 ();
}
public static void Main (string[] args) {
Singleton S1 =new Singleton ();
Singleton1 S1 = singleton1.s;
Singleton1 s2 = singleton1.s;
System.out.println (S1 = = s2);
}
# 整合
Package com.heima.thread;
public class Demo1_singleton {
/** * @param args * * 单例设计模式:保证类在内存中只有一个对象。 */public static void main(String[] args) { //Singleton s1 = new Singleton(); Singleton s1 = Singleton.s; //成员变量被私有,不能通过类名.调用 //Singleton.s = null; Singleton s2 = Singleton.s; System.out.println(s1 == s2);/* Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); System.out.println(s1 == s2);*/}
}
/*
Class Singleton {
1, private constructor method, other classes cannot access the constructor.
Private Singleton () {}
2, create this class object
private static Singleton s = new Singleton ();
3, provide public access to external methods
public static Singleton getinstance () {//Get instance
return s;
}
}/
/
-
Lazy, single-case delay-loading mode
/
/class Singleton {
1, private constructor method, other classes cannot access the constructor.
Private Singleton () {}
2, declare a reference
private static Singleton s;
3, provide public access to external methods
public static Singleton getinstance () {//Get instance
if (s = = null) {
Thread 1 waits, thread 2 waits
s = new Singleton ();
}
return s;
}
}/
/
- The difference between a hungry man and lazy-type
- 1, a hungry man type is space change time, lazy type is time change space
- 2, in multi-threaded access, a hungry man does not create multiple objects, while lazy-type may create multiple objects
*/
Class Singleton {
1, private constructor method, other classes cannot access the constructor.
Private Singleton () {}
2, declare a reference
public static final Singleton s = new Singleton ();
}
Java single-instance design pattern learning