1.最基本的单例模式
/** * @author LearnAndGet * @time 2018年11月13日 * 最基本的单例模式 */public class SingletonV1 { private static SingletonV1 instance = new SingletonV1();; //构造函数私有化 private SingletonV1() {} public static SingletonV1 getInstance() { return instance; } }
import org.junit.Test; public class SingletonTest { @Test public void test01() throws Exception { SingletonV1 s1 = SingletonV1.getInstance(); SingletonV1 s2 = SingletonV1.getInstance(); System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); } } //运行结果如下:589873731589873731
2.类加载时不初始化实例的模式
上述单例模式在类加载的时候,就会生成实例,可能造成空间浪费,如果需要修改成,在需要使用时才生成实例,则可修改代码如下:
1 public class SingletonV2 { 2 3 private static SingletonV2 instance; 4 5 //构造函数私有化 6 private SingletonV2() {} 7 8 public static SingletonV2 getInstance(){ 10 if(instance == null) 11 { 12 instance = new SingletonV2(); 13 } 14 return instance; 15 }

