单例模式

来源:互联网 发布:超级电容给单片机供电 编辑:程序博客网 时间:2024/06/16 10:47

单例模式

简单地说,单例模式就是实现单例模式的这个类只有一个实例对象,每次返回的都是同一个对象。在数据库连接的应用场景中,单例模式避免了反复生成数据库连接对象这种情况的发生,能够起到节约资源的作用

懒汉模式

第一次被引用时,才会被实例化,需要考虑多线程问题可以用双重锁来实现同步并提高同步的效率
  1. public class Singleton {
  2. private static Singleton instance;
  3. private Singleton(){}
  4. public static Singleton getInstance(){
  5. if(instance==null){
  6. synchronized (Singleton.class) {
  7. if(instance==null)
  8. instance=new Singleton();
  9. }
  10. }
  11. return instance;
  12. }
饿汉模式
类加载的时候就实例化,提前占用系统资源
  1. class Singleton{
  2. private static Singleton instance=new Singleton();
  3. private Singleton(){}
  4. public static Singleton getInstance(){
  5. return instance;
  6. }
  7. }

原创粉丝点击