单例模式
Posted wpf0414
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式相关的知识,希望对你有一定的参考价值。
//1.懒汉模式 public class SingletonDemo { private static SingletonDemo instance; private SingletonDemo(){ } public static SingletonDemo getInstance(){ if(instance==null){ instance=new SingletonDemo(); } return instance; } } //2. 线程安全的懒汉模式 public class SingletonDemo { private static SingletonDemo instance; private SingletonDemo(){ } public static synchronized SingletonDemo getInstance(){ if(instance==null){ instance=new SingletonDemo(); } return instance; } } //3.饿汉 public class SingletonDemo { private static SingletonDemo instance=new SingletonDemo(); private SingletonDemo(){ } public static SingletonDemo getInstance(){ return instance; } }
以上是关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章