当前位置:编程学习 > JAVA >>

[Android面试题-7] 写出一个Java的Singleton类(即单例类)

1.首先明确单例的概念和特点:
 
a>单例类只能有一个实例
 
b>单例类必须自己创建一个自己的唯一实例
 
c>单例类必须为其他所有对象提供这个实例
 
 
2.单例具有几种模式,最简单的两种分别是“懒汉式”和“饿汉式”:
 
懒汉式:不会主动创建自己的实例,等待第一次被调用时创建
 
饿汉式:主动创建自己的实例。
 
 
3.两个模式的例子:
 
懒汉式:
 
 
 
public class Singleton {  
    private static Singleton uniqueInstance = null;  
   
    private Singleton() {  
       // Exists only to defeat instantiation.  
    }  
   
    public static Singleton getInstance() {  
       if (uniqueInstance == null) {  
           uniqueInstance = new Singleton();  
       }  
       return uniqueInstance;  
    }  
    // Other methods...  
}  

 

 
饿汉式:
 
class Singleton {  
  private static Singleton instance=new Singleton();  
  private Singleton(){}  
  static Singleton getInstance() {  
      return instance;  
  }  
}  

 

 
补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,