【发布时间】:2014-03-13 11:39:25
【问题描述】:
多年来,我将其称为 flyweight,但在寻找对 flyweight 的良好描述时,我注意到他们都说基本用例是创建许多轻量级对象,而我的动机是避免创建大量对象。
该模式是关于使用一个对象或少量对象在特定接口的伪装下顺序引用更大数据结构的不同部分。例如,下面是一个对象类,它为我提供了一个 Number 对象,该对象引用字节数组的部分(一次一个部分)来获取其实际数据:
public final class LittleEndRef extends Number {
private byte[] a;
private int off;
// This is the point: the fields are not finals, set in a constructor, which would require
// creating a new object every time I want to address some postion of an array. I reuse the
// same object to refer to different positions. (My motivation is to ensure that there is no
// overhead from garbage collection, ever.)
void setRef(byte[] a, int off) { this.a = a; this.off = off; }
public byte byteValue() { return a[off]; }
public short shortValue() { return (short)(a[off] | a[off+1]<<8); }
public int intValue() { return a[off] | a[off+1]<<8 | a[off+2]<<16 | a[off+3]<<24; }
public long longValue() { return a[off] | a[off+1]<<8 | a[off+2]<<16 | a[off+3]<<24 |
(long)(a[off+4] | a[off+5]<<8 | a[off+6]<<16 | a[off+7]<<24)<<32; }
public float floatValue() { return Float.intBitsToFloat(intValue()); }
public double doubleValue() { return Double.longBitsToDouble(longValue()); }
}
您可以说这是一个适配器,但它是一种特殊的适配器,因为它引用较大存储的一部分而不复制数据,并且它可以更改为引用不同的部分,而无需创建新对象。
我应该如何引用该模式?
【问题讨论】:
-
它不会受到竞争条件的严重影响吗? IE。它似乎不是线程安全的
-
是的,你绝对不应该在线程之间传递这些对象。
标签: java design-patterns