设计模式-享元模式

什么是享元模式
享元 顾名思义就是共享同一个单元;目的是复用对象,节省内存,前提是享元对象是不可变的

Java中常见的享元模式运用
Integer相关运用

public static void main(String[] args) {
        Integer i1 = 56;
    Integer i2 = new Integer(56);
    Integer i3 = 56;
    Integer i4 = 129;
    Integer i5 = 129;
    System.out.println(i1 == i2); //true
    System.out.println(i1 == i3); //false
    System.out.println(i4 == i5); //false
   }
第一个为true的原因是我们通过自动装箱,调用valueOf()来创建Integer对象是,如果对象的值在-128~127之间,那么会从IntegerCache类中直接返回,否则才调用new 方法创建,详情可见Integer.valueOf()源码
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
 private static class IntegerCache {
      static final int low = -128; //缓存的最小值
      static final int high; //缓存的最大值
      static final Integer cache[];  //缓存

      static {
          // high value may be configured by property
          int h = 127;
          String integerCacheHighPropValue =
              sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
          if (integerCacheHighPropValue != null) {
              try {
                  int i = parseInt(integerCacheHighPropValue);
                  i = Math.max(i, 127);
                  // Maximum array size is Integer.MAX_VALUE
                  h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
              } catch( NumberFormatException nfe) {
                  // If the property cannot be parsed into an int, ignore it.
              }
          }
          high = h;

          cache = new Integer[(high - low) + 1];
          int j = low;
          for(int k = 0; k < cache.length; k++)
              cache[k] = new Integer(j++);

          // range [-128, 127] must be interned (JLS7 5.1.7)
          assert IntegerCache.high >= 127;
      }

      private IntegerCache() {}
  }

由此可以看出当加载Integer对象时该内部类也被加载进去,从而缓存了-128到127之间的整型值。(Long,Short,Byte也有相应的处理)
String的相关应用

  public static void main(String[] args) {
    String s1 = "享元模式";
    String s2 = "享元模式";
    String s3 = new String("享元模式");

    System.out.println(s1 == s2); //ture
    System.out.println(s1 == s3); //false
  }

前两个s1和s2都是指向字符串常量“享元模式”,s3指的是堆的String r
String类中享元在设计上有所不同,Integer类中要共享对象,是在类加载的时候,就集中一次性创建好的;但对于字符串来说,无法事先知道要共享哪些字符串变量,所以没办法事先创建,只能在某一个字符串首次被用到的时候,存储到常量池中,之后在用到时,直接引用常量池中存在的即可。

原文地址:https://www.cnblogs.com/lch-Hao/p/14503993.html