For years, I referred to this as flyweight , but looking for a good description of flyweight, I noted that they all said the basic use case was to create a lot of lightweight objects, whereas my motivation is to avoid creating a lot of objects.
The pattern is about using one object, or a small number of objects, for sequentially referring to different parts of a larger data structure under the guise of a specific interface. For instance, here is a class for an object that gives me a Number object that refers to parts (one part at a time) of a byte array for its actual data:
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()); }
}
You could say this is an adapter, but it's a special kind of adapter in that it refers to part of a larger storage without duplicating the data, and also that it can be changed to refer to a different part, without creating a new object.
Any takes on how I should refer to that pattern?
轻盈的花纹感觉像装饰图案
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.