简单总结单例模式的4种写法
一、单例模式
属于创建者模式的一种, 单例模式的目的是使该类只有一个实例,同一个类的不同对象有不同的hashCode()
单例模式是由该类自行创建唯一个向外暴露的全局的对象
二、写法
三、饿汉式
/** * 饿汉式: * 不适用new创建对象而是使用静态的getInstance()方法创建对象 * jvm保证线程安全 */ public class SingleTest{ public static void main(String[] args) { Single single1 = Single.getInstance(); Single single2 = Single.getInstance(); System.out.println(single1.hashCode()); System.out.println(single2.hashCode()); System.out.println(single1 == single2); } } class Single { final static Single INSTANCE = new Single(); public static Single getInstance(){return INSTANCE;} }
四、懒汉式
//懒汉式的线程安全的写法又称为双检索懒汉模式 public class SingleTest { public static void main(String[] args) { for(int i = 0;i < 10; i++){ new Thread(new Runnable() { @Override public void run() { System.out.println(Single.getInstance().hashCode()); } }).start(); } } } class Single{ private static Single instance = null; Single(){} public static Single getInstance(){ if (instance == null){ synchronized (Single.class) { if(instance == null){ try{ Thread.sleep(1); }catch (Exception e){ e.printStackTrace(); } instance = new Single(); } } } return instance; } }
五、内部类
/** * 静态内部类:完美写法 */ public class SingleTest { public static void main(String[] args) { Single single1 = Single.getInstance(); Single single2 = Single.getInstance(); System.out.println(single1.hashCode()); System.out.println(single2.hashCode()); System.out.println(single1 == single2); } } class Single{ private static Single instance; public static Single getInstance(){ return InnerSingle.INSTANCE; } private static class InnerSingle{ private final static Single INSTANCE = new Single(); } }
六、枚举
//枚举:完美写法 public class SingleTest { public static void main(String[] args) { Single single1 = Single.INSTANCE; Single single2 = Single.INSTANCE; System.out.println(single1.hashCode()); System.out.println(single2.hashCode()); System.out.println(single1 == single2); } } enum Single{ INSTANCE; }
七、结论
优点:
缺点:
到此这篇关于简单总结单例模式的4种写法的文章就介绍到这了,更多相关单例模式的4种写法内容请搜索趣讯吧以前的文章或继续浏览下面的相关文章希望大家以后多多支持趣讯吧!