我一直在寻找享元模式的实现,并在到达 Google 搜索的第 20 页后放弃了。虽然那里有无数愚蠢的例子,但似乎没有人发布过 Java 中的可重用实现。
对我来说,flyweight 只有在您必须保留许多这样的实例 时才真正有意义,因此它必须作为一个集合来实现。我想要的是一个采用 byte/short/int/long mapper 实现并返回 List、Set 或 Map 的工厂,它看起来像一个普通的对象集合,但在内部存储它的数据作为原始数组,从而节省了大量内存。映射器将采用 X 类型的对象,并将其映射到基元,或者以相反的方式进行。
哪里有类似的东西?
[编辑] 我正在寻找支持此模式的Collection 库,而不仅仅是任何示例,其中有数百个。
如果要替换List,可以改用TByteArrayList。如果你想替换 List where MyClass { int a; T对象;您可以改用 TIntObjectHashMap。
如果你想用两个必须排序的字段或三个或更多字段替换某些东西,你需要实现你自己的类来包装数组来保存数据。这是使用基于列的表模型。
例如
class MyClass {
byte b;
int i;
String s;
}
class MyClassList {
int size = 0;
int capacity;
byte[] bytes;
int[] ints;
String[] strings;
MyClassList(int capacity) {
this.capacity = capacity;
}
public void add(MyClass myClass) {
if (size == capacity) resize();
bytes[size] = myClass.b;
ints[size] = myClass.i;
strings[size] = myClass.s;
size++;
}
public void get(MyClass myClass, int index) {
if (index > size) throw new IndexOutOfBoundsException();
myClass.b = bytes[index];
myClass.i = ints[index];
myClass.s = strings[index];
}
}
从 Java 5.0 开始,自动装箱缓存就是享元的例子。
Integer i1 = 1;
Integer i2 = 1;
System.out.println(i1 == i2); // true, they are the same object.
Integer i3 = -200;
Integer i4 = -200;
System.out.println(i3 == i4); // false, they are not the same object.
如果您想阅读代码,请在您的 IDE 中查看 Integer.valueOf(int) 或
http://www.docjar.com/html/api/java/lang/Integer.java.html第638行
编辑:
Integer 的自动装箱使用 IntegerCache,它是一个集合。 ArrayList 是一个包装数组并具有大小的类...
private static class IntegerCache {
static final int high;
static final Integer cache[];