懶漢式單例模式(lazy singleton)
單例類文件StudentSingleton.java
package com.dou361.singleton;
/**
* @author Admin
*懶漢單例模式
*/
public class StudentSingleton {
private static StudentSingleton studentSingleton = null;
private StudentSingleton(){}
public static synchronized StudentSingleton getInstance() {
if(studentSingleton != null) {
return studentSingleton;
} else {
return studentSingleton = new StudentSingleton();
}
}
public void getName() {
System.out.println("我是賴漢單例模式");
}
public void getGender() {
System.out.println("我是爺們");
}
}
測試類文件Test.javapackage com.dou361.test;
import com.dou361.singleton.StudentSingleton;
public class Test {
public static void main(String[] args) {
StudentSingleton studentSingleton = StudentSingleton.getInstance();
studentSingleton.getName();
studentSingleton.getGender();
StudentSingleton student = StudentSingleton.getInstance();
student.getName();
student.getGender();
//判斷是否是單例
System.out.println(studentSingleton.equals(studentSingleton));
}
}