先上代码:
 
 1 package com.test.singleton;
 2 
 3 /**
 4  * @author mr.cheng
 5  *
 6  */
 7 public class Singleton {
 8     //运用private私有化构造器,其他类不能通过new获取本对象
 9     private Singleton() {
10     }
11     //运用私有静态instance保存本对象,必须是静态变量,因为会在getInstance方法中运用
12     private  static Singleton instance;
13     //静态方法是因为不能通过new来获取对象,只能通过这个静态方法来获取对象实例
14     static synchronized Singleton getInstance(){
15         //先判断保存实例的变量instance是否为空,为空则新建实例,并保存到instance中
16         if(instance == null){
17             //Singleton只有一个构造器,并声明为private,因此只能在内部调用new 获取实例
18             instance = new Singleton();
19             return instance;
20         } else{
21             return instance;
22         }
23     }
24 }
25 
单列模式主要运用场景:实例化时耗用的资源比较大,或者对象实例比较频繁,以及要保证在整个程序中,只有一个实例。
 例如数据源配置,系统参数配置等。