Java之单例模式(Singleton)

摘要:

  1.Singleton模式作用:保证在Java应用程序中,一个Class只有一个实例存在

  2.Singleton的第一种形式:饿汉式单例模式

      (1) 构造函数私有

      (2)有一个static 的private的该类的变量

      (3)通过一个public getInstance的方法获取对它的引用

      代码如下:

      

 1 package com.ggzhang.Test;
 2 
 3 public class Singleton {
 4 
 5     private Singleton() {
 6 
 7     }
 8 
 9     private static Singleton instance = new Singleton();
10 
11     public static Singleton getInstance() {
12         return instance;
13     }
14 }

  3.Singleton的第二种形式:懒汉式单例模式

    (1)先判断一下instance是否被创建.如果创建了就返回,如果没创建就创建,不用每次都进行生成对象,只是第一次使用时生成实例,提高了效率

 1 package com.ggzhang.Test;
 2 
 3 public class Singleton2 {
 4 
 5     private Singleton2() {
 6 
 7     }
 8 
 9     private static Singleton2 instance = null;
10 
11     public static Singleton2 getInstance() {
12         if(instance == null){
13             instance = new Singleton2();
14         }
15         return instance;
16     }
17 }
原文地址:https://www.cnblogs.com/ggzhangblog/p/6368286.html