什么事享元模式
享元模式(Flyweight Pattern)是面向对象设计模式中的一种,用于支持大量细粒度对象的复用,以减少内存占用和提高性能。享元模式的核心思想是存储和共享细粒度状态(内在状态),同时将粗粒度状态(外在状态)传递给这些细粒度对象。
需了解一定的jvm知识
Integer中,享元模式指定的区间([-128, 127])
public static void main(String[] args) {
Integer a = IntegerFlyweight.get(100);
Integer b = IntegerFlyweight.get(100);
System.out.println(a == b); // 输出 true,因为100在缓存区间内
Integer c = IntegerFlyweight.get(200);
Integer d = IntegerFlyweight.get(200);
System.out.println(c == d); // 输出 false,因为200不在缓存区间内
}
Long中,享元模式指定的区间内([-1000, 1000])
public static void main(String[] args) {
Long a = LongFlyweight.get(500L);
Long b = LongFlyweight.get(500L);
System.out.println(a == b); // 输出 true,因为500L在缓存区间内
Long c = LongFlyweight.get(2