标签:div 注意 image ret zed 测试 图片 int 静态方法
//饿汉式(静态变量) public class SigletonType01 { //1.构造器私有化,外部不能new private SigletonType01(){ } //2.本类内部创建对象实例 private final static SigletonType01 instance = new SigletonType01(); //3.提供一个公有的静态方法,返回实例对象 public static SigletonType01 getInstance(){ return instance; } }
@Test public void test01(){ SigletonType01 sigletonType01 = SigletonType01.getInstance(); SigletonType01 sigletonType011 = SigletonType01.getInstance(); System.out.println(sigletonType01 == sigletonType011); System.out.println(sigletonType01.hashCode()); System.out.println(sigletonType011.hashCode()); /* 结果: true 1568059495 1568059495 */ }
//饿汉式(静态代码块) public class SigletonType02 { //1.构造器私有化,外部不能new private SigletonType02(){ } //2.静态代码块中创建实例 private final static SigletonType02 instance; static{ instance = new SigletonType02(); } //3.提供一个公有的静态方法,返回实例对象 public static SigletonType02 getInstance(){ return instance; } }
//懒汉式(线程不安全) public class SigletonType03 { //1.构造器私有化,外部不能new private SigletonType03(){ } //2.静态代码块中创建实例 private static SigletonType03 instance; //3.提供一个公有的静态方法,返回实例对象 public static SigletonType03 getInstance(){ if(instance == null){ instance = new SigletonType03(); } return instance; } }
//懒汉式(线程安全,同步代码) public class SigletonType04 { private SigletonType04(){ } private static SigletonType04 instance; //synchronized 同步代码,解决线程不安全问题 public static synchronized SigletonType04 getInstance(){ if(instance == null){ instance = new SigletonType04(); } return instance; } }
public class SigletonType05 { private SigletonType05(){ } private static SigletonType05 instance; //synchronized 同步代码块 public static SigletonType05 getInstance(){ if(instance == null){ synchronized (SigletonType05.class){ instance = new SigletonType05(); } } return instance; } }
public class SigletonType06 { private SigletonType06(){ } private static volatile SigletonType06 instance; public static SigletonType06 getInstance(){ if(instance == null){ synchronized (SigletonType06.class){ if(instance == null){ instance = new SigletonType06(); } } } return instance; } }
public class SigletonType07 { private SigletonType07(){ } public static class SigletonInstance{ private static final SigletonType07 instance = new SigletonType07(); } public static SigletonType07 getInstance(){ return SigletonInstance.instance; } }
enum SigletonType08 { INSTANCE; public void method(){ System.out.println("method"); } }
标签:div 注意 image ret zed 测试 图片 int 静态方法
原文地址:https://www.cnblogs.com/zhihaospace/p/12452647.html