对单例模式的理解

单例模式在实际生产中有重要的作用

  懒汉模式:

 1 public class SingleClassOne// TODO 懒汉模式  类加载时候创建单例对象 赋值为null
 2 {
 3     private static SingleClassOne instance = null; // 私有静态对象属性
 4 
 5     private SingleClassOne(){} // 私有构造器
 6     public static synchronized SingleClassOne getInstance() // 私有静态get()方法 TODO                                                    
 7     {
 8         if (instance == null)
 9         {
10             instance = new SingleClassOne();    // 单例对象在第一次使用get方法时被实例化
11         }
12         return instance;
13     }
14 
15 }

  教材上的例子:

 1 public class Company//教材上的单例模式
 2 {
 3     private Company(){}
 4     
 5     private static Company company = new Company();//单例对象在类加载时被实例化
 6     
 7     public static Company getCompany()                //静态get()方法得到company单例对象
 8     {
 9         return company;
10     }
11 }

 

posted on 2015-11-13 22:22  starFarming  阅读(162)  评论(0编辑  收藏  举报