这种模式的名称是什么? (重复使用轻量级)

时间:2014-03-13 11:39:26

标签: java design-patterns

多年来,我将此称为 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()); }
}

你可以说这是一个适配器,但它是一种特殊的适配器,因为它指的是较大存储的一部分而不复制数据,并且它可以被更改为引用不同的部分,而不创建新对象。

我应该如何引用该模式?

1 个答案:

答案 0 :(得分:0)

感觉像Flyweight Pattern的装饰图案