先上代码:
package com.test.singleton; /** * @author mr.cheng * */ public class Singleton { //运用private私有化构造器,其他类不能通过new获取本对象 private Singleton() { } //运用私有静态instance保存本对象,必须是静态变量,因为会在getInstance方法中运用 private static Singleton instance; //静态方法是因为不能通过new来获取对象,只能通过这个静态方法来获取对象实例 static synchronized Singleton getInstance(){ //先判断保存实例的变量instance是否为空,为空则新建实例,并保存到instance中 if(instance == null){ //Singleton只有一个构造器,并声明为private,因此只能在内部调用new 获取实例 instance = new Singleton(); return instance; } else{ return instance; } } }单列模式主要运用场景:实例化时耗用的资源比较大,或者对象实例比较频繁,以及要保证在整个程序中,只有一个实例。 例如数据源配置,系统参数配置等。