枚举实现单例简单例子

枚举类:

import java.util.Date;  
  
  
public enum Datetest{  
    INSTANCE;  
    private Date d;  
    private  animal(){  
     d=new Date();  
        System.out.println("调用了构造方法");  
          
    }  
    public Date builddate(){    
          
        return d;    
    }    
}  


 
  

然后定义一个类来调用它

import java.util.*;  
  
public class test{  
    public static void main(String args[]){  
      
    Date d=animal.INSTANCE.buildAnimalList();  
    Date d1=animal.INSTANCE.buildAnimalList();  
    System.out.println(d.toString()+"  "+d1.toString());  
    d1.setHours(11);  
    System.out.println(d.equals(d1));  
    System.out.println(d.toString()+"  "+d1.toString());  
    }  
}  
结果
调用了构造方法  
Mon Jun 29 10:47:45 GMT+08:00 2015  Mon Jun 29 10:47:45 GMT+08:00 2015  
true  
Mon Jun 29 11:47:45 GMT+08:00 2015  Mon Jun 29 11:47:45 GMT+08:00 2015  



你可能感兴趣的:(java)