饿汉单例模式
SingleInstance
package com.ITheima._static_codeblock; public class SingleInstance { /** * 1 把无参构造器私有藏起来 */ private SingleInstance(){ } /** * 2 定义一个公开的静态的成员变量存储一个类的对象 * 饿汉:在这里加载静态变量的时候就会创建对象了 */ public static SingleInstance instance=new SingleInstance(); }View Code
Test类
package com.ITheima._static_codeblock; public class Test { public static void main(String[] args) { SingleInstance s1=SingleInstance.instance; SingleInstance s2=SingleInstance.instance; SingleInstance s3=SingleInstance.instance; System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s1 == s2 && s2 == s3);//true } }View Code
懒汉单例模式
SingleInstance1类
package com.ITheima._static_codeblock; public class SingleInstance1 { //1 私有化构造器 private SingleInstance1() { } //2 创建一个静态的成员变量存储类的对象,注意此时不能初始化对象 private static SingleInstance1 instance = null; //3定义一个方法 ,让其他地方可以来调用获取一个对象 public static SingleInstance1 getInstance() { //第一次获取对象 if (instance == null) { instance = new SingleInstance1(); } return instance; } }View Code
Test1类
package com.ITheima._static_codeblock; public class Test1 { public static void main(String[] args) { SingleInstance1 s1 = SingleInstance1.getInstance(); SingleInstance1 s2 = SingleInstance1.getInstance(); SingleInstance1 s3 = SingleInstance1.getInstance(); System.out.println(s1 == s2 && s2 == s3);//true } }View Code