1. /*  
  2.     缓存实例的不可变类  
  3. */ 
  4. public class CacheImmutale  
  5. {  
  6.     private final String name;  
  7.     private static CacheImmutale[] cache = new CacheImmutale[10];  
  8.     //记录缓存实例在缓存中的位置,cache[pos-1]是最新缓存的实例  
  9.     private static int pos = 0;  
  10.     public CacheImmutale(String name)  
  11.     {  
  12.         this.name = name;     
  13.     }     
  14.     public String getName()  
  15.     {  
  16.         return name;      
  17.     }  
  18.     public static CacheImmutale valueOf(String name)  
  19.     {  
  20.         //遍历已缓存的对象  
  21.         for (int i = 0 ; i < pos;i++)  
  22.         {  
  23.             //如果已有相同的实例,直接返回该缓存的实例  
  24.             if(cache[i] != null && cache[i].getName().equals(name))  
  25.             {  
  26.                 return cache[i];      
  27.             }     
  28.             //如果缓存池已满  
  29.             if(pos == 10)  
  30.             {  
  31.                 //把缓存池的第一个对象覆盖  
  32.                 cache[0] = new CacheImmutale(name);  
  33.                 post = 1;  
  34.                 return cache[0];      
  35.             }  
  36.             else 
  37.             {  
  38.                 //把新创建的对象缓存起来,pos加1  
  39.                 cache[pos++] = new CacheImmutale(name);  
  40.                 return cache[pos - 1];  
  41.             }  
  42.         }     
  43.         public boolean equals(Object obj)  
  44.         {  
  45.             if(obj instanceof CancheImmutale)  
  46.             {  
  47.                 CacheImmutale ci = (CacheImmutale)obj;  
  48.                 if(name.equals(ci.getName()))  
  49.                 {  
  50.                     return true;      
  51.                 }     
  52.             }     
  53.             return false;  
  54.         }  
  55.         public int hashCode()  
  56.         {  
  57.             return name.hashCode();   
  58.         }  
  59.         public static void main(String[] args)  
  60.         {  
  61.             CacheImmutale c1 = CacheImmutale.valueOf("hello");  
  62.             CacheImmutale c2 = CacheImmutale.valueOf("hello");  
  63.             System.out.println(c1 == c2);//true  
  64.         }  
  65.     }