餓漢式單例模式(hunger singleton)
單例類文件StudentSingleton.java
package com.dou361.singleton;
/**
* @author Admin
*餓漢單例模式
*/
public class StudentSingleton {
//已經自行實例化
private static StudentSingleton studentSingleton = new StudentSingleton();
//私有的默認構造
private StudentSingleton() {}
//靜態工廠方法
public static final StudentSingleton getInstance() {
return studentSingleton;
}
public void getName() {
System.out.println("我是一個單例小案例");
}
public void getGender() {
System.out.println("我是爺們");
}
}
測試類文件Test.java
package 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));
}
}