JAVA-单例设计模式

目的:

单例模式主要是为了避免因为创建了多个实例造成资源的浪费,且多个实例由于多次调用容易导致结果出现错误,而使用单例模式能够保证整个应用中有且只有一个实例。

单例模式的设计思想:

(1)不允许其他程序用new对象。

因为new就是开辟新的空间,在这里更改数据只是更改的所创建的对象的数据,如果可以new的话,每一次new都产生一个对象,这样肯定保证不了对象的唯一性。

(2)在该类中创建对象

因为不允许其他程序new对象,所以这里的对象需要在本类中new出来

(3)对外提供一个可以让其他程序获取该对象的方法

因为对象是在本类中创建的,所以需要提供一个方法让其它的类获取这个对象。

将上述三步转换成代码描述是这样的:

(1)私有化该类的构造函数


(2)通过new在本类中创建一个本类对象
(3)定义一个公有的方法,将在该类中所创建的对象返回

单例模式的写法:

①懒汉式②饿汉式③双重校验锁④静态内部类⑤枚举

1.单例模式的饿汉式:

创建:

<code>public class Singleton {
      private static Singleton instance=new Singleton();
      private Singleton(){};
      public static Singleton getInstance(){
        		return instance;
      }
}/<code>
<code>访问方式/<code>

优点:从它的实现中我们可以看到,这种方式的实现比较简单,在类加载的时候就完成了实例化,避免了线程的同步问题。

缺点:由于在类加载的时候就实例化了,所以没有达到Lazy Loading(懒加载)的效果,也就是说可能我没有用到这个实例,但是它

也会加载,会造成内存的浪费(但是这个浪费可以忽略,所以这种方式也是推荐使用的)。

单例模式的饿汉式变换写法:

<code>public class Singleton{
 
	private static Singleton instance = null;
	
	static {
		instance = new Singleton();
	}
 
	private Singleton() {};
 
	public static Singleton getInstance() {
		return instance;
	}
}/<code>

访问方式:

<code>Singleton instance = Singleton.getInstance();/<code>

单例模式的懒汉式[线程不安全,不可用]

<code>
public class Singleton {
 
	private static Singleton instance=null;
	
	private Singleton() {};
	
	public static Singleton getInstance(){
		
		if(instance==null){
			instance=new Singleton();
		}
		return instance;
	}
}/<code>

懒汉式线程安全的[线程安全,效率低不推荐使用]

<code>
public class Singleton {
 
	private static Singleton instance=null;
	
	private Singleton() {};
	
	public static synchronized Singleton getInstance(){
		
		if(instance==null){
			instance=new Singleton();
		}
		return instance;
	}
}/<code>

内部类[推荐用]

<code>public class Singleton{
 
	
	private Singleton() {};
	
	private static class SingletonHolder{
		private static Singleton instance=new Singleton();
	} 
	
	public static Singleton getInstance(){
		return SingletonHolder.instance;
	}
}/<code>

访问方式:

<code>/<code>

枚举[极推荐使用]

<code>
public enum SingletonEnum {
	
	 instance; 
	 
	 private SingletonEnum() {}
	 
	 public void method(){
	 }
}/<code>

访问方式

<code>/<code>
JAVA-单例设计模式


<code>对称的美感/<code>


分享到:


相關文章: