Java设计模式---单例模式

Java设计模式---单例模式

 

1.饿汉式

     

package com.ooad.sington;

/**
 * 饿汉式单例模式
 * @author Administrator
 *
 */
public class Sington1 {
	
	private Sington1(){
		
	}
	
	private static Sington1 sington = new Sington1();
	
	public static Sington1 getInstance(){
		
		return sington;
	}

}

 

 

 

  2.懒汉式(延迟加载)

   

package com.ooad.sington;

/*
 * 懒汉式(延迟加载)
 */
public class Sington2 {
	
	private Sington2(){
		
	}
	
	private static Sington2 sington = null;
	
	public static synchronized Sington2 getInstance(){
		
		if(sington == null){
			sington = new Sington2();
		}
		return sington;
	}

}

 

 

 3.双锁机制(解决懒汉式在高并发量下效率问题)

 

   

package com.ooad.sington;

/**
 * 双锁机制
 * @author Administrator
 *
 */
public class Sington3 {

	private Sington3(){
		
	}
	
	private static Sington3 sington = null;
	
	public static Sington3 getInstance(){
		
		if(sington == null){
			synchronized(Sington3.class){
				sington = new Sington3();
			}
		}
		return sington;
	}
}

 

   

你可能感兴趣的:(java,设计模式)