設計模式案例--單例模式--懶漢式單例模式(lazy singleton)

懶漢式單例模式(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.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));
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章