享原模式

38 阅读2分钟

享原模式的目的

为了解决大量创建相同对象,可能造成OOM

优点

减少重复创建对象,降低内存

缺点

提高了系统的复杂度,如果固定了一些对象,当被改变时候,会造成混乱

//假设有个请求的类
public class Request {
}
//通过一个地方 去拿请求
public class HttpFactory {
    public static final HashMap<String,Request> requestMap = new HashMap<>();

    public Request getRequestList(String name) {
        Request request = (Request) requestMap.get(name);
        if(request==null){
            request = new Request();
            requestMap.put(name,request);
        }
        return request;
    }
}
//使用
HttpFactory factory = new HttpFactory();
Request request1 = factory.getRequestList("baidu");
//假设过了一会
Request request2 = factory.getRequestList("baidu");

相当于是缓存了一块地方,把对象放进去,需要对象的时候就从这里面取,如果相同需求,则会返回已有的对象。
在android中,获取Message,可以通过Message.obtain()去获取Message。在JVM中缓存了很多字符串。

以Integer类为例

Integer类使用了享元模式

public static void main(String[] args) {
        Integer i1 = 127;
        Integer i2 = 127;

        System.out.println("i1和i2对象是否是同一个对象?" + (i1 == i2));

        Integer i3 = 128;
        Integer i4 = 128;

        System.out.println("i3和i4对象是否是同一个对象?" + (i3 == i4));
}

结果是 true false

通过反编译可以看到,直接给Integer类型的变量赋值基本数据类型数据的操作底层使用的是 valueOf()。

public static void main(String[] args) {
        Integer i1 = Integer.valueOf((int)127);
        Integer i2 = Integer.valueOf((int)127);
        System.out.println((String)new StringBuilder().append((String)"i1\u548ci2\u5bf9\u8c61\u662f\u5426\u662f\u540c\u4e00\u4e2a\u5bf9\u8c61\uff1f").append((boolean)(i1 == i2)).toString());
        Integer i3 = Integer.valueOf((int)128);
        Integer i4 = Integer.valueOf((int)128);
        System.out.println((String)new StringBuilder().append((String)"i3\u548ci4\u5bf9\u8c61\u662f\u5426\u662f\u540c\u4e00\u4e2a\u5bf9\u8c61\uff1f").append((boolean)(i3 == i4)).toString());
}

valueOf()

public final class Integer extends Number implements Comparable<Integer> {
    
	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 {
            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) {
                }
            }
            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 之间数的 Integer 对象,当调用 valueOf 时如果参数在 -128 ~ 127 之间则计算下标并从缓存中返回,否则创建一个新的 Integer 对象。