設計模式之-單例模式-Singlecon

悠悠隱於市發表於2011-04-17
package pack.java.singlecon.demo;
/**
 * 單例模式;
 * @author Administrator
 *
 */
public class Singlecon {
	
	private static Singlecon SINGLECON = null;
	/**
	 * 靜態私有的構造方法;
	 */
	private Singlecon(){
		
	}
	
	/**
	 * 構造出一個例項;
	 * @return
	 */
	public synchronized static Singlecon getInstance(){
		if(SINGLECON == null){
			SINGLECON = new Singlecon();
		}
		return SINGLECON;
	}
	
	/**
	 * 主方法;
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Singlecon singlecon = Singlecon.getInstance();
		Singlecon singlecon2  = Singlecon.getInstance();
		
		System.out.println(singlecon);
		System.out.println(singlecon2);
		
		if(singlecon == singlecon2 ){
			System.out.println("屬於同一個例項!");
		}
	}

}

 

 

結果:

pack.java.singlecon.demo.Singlecon@35ce36
pack.java.singlecon.demo.Singlecon@35ce36
屬於同一個例項!

相關文章