开发者

Is there any Java flyweight pattern implementation out there? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, 开发者_如何转开发 visit the help center. Closed 11 years ago.

I've been looking for a flyweight pattern implementation and gave up after reaching page 20 of Google search. While there are countless stupid examples out there, it seems no one has ever published are reusable implementation in Java.

For me, flyweight really only makes sense if you have to keep many such instances, so it has to be implemented as a collection. What I would like is a Factory that takes a byte/short/int/long mapper implementation, and returns either a List, Set or Map, that looks like a normal Object collection, but stores it's data internally as an array of primitive, thereby saving lots of ram. The mapper would take an object of type X, and map it to a primitive, or do it the other way around.

Is there something like that available somewhere?

[EDIT] I am looking for a Collection library that support this pattern, not just any example, of which there are hundreds.


If you want to replace List, you can use TByteArrayList instead. If youw ant to replace List where MyClass { int a; T object; } you can use TIntObjectHashMap instead.

If you want to replace something with two fields which must be ordered or three or more fields, you need to implement your own class which wraps arrays to hold the data. This is using a column based table model.

e.g.

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];
    }
}

From Java 5.0, the auto-boxing caches are examples of flyweights.

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.

If you want to read the code, have a look at Integer.valueOf(int) in your IDE or http://www.docjar.com/html/api/java/lang/Integer.java.html line 638

EDIT: Autoboxing for Integer uses IntegerCache which is a collection. An ArrayList is a class which wraps an array and has a size...

private static class IntegerCache {
    static final int high;
    static final Integer cache[];


I think, Integer.valueOf(String s) is quite a flyweight. Because, as far as I know, it keeps some amount of the created Integers internally, so, when you pass the String that you have passed before - it returns you an existing instance.


Have you seen Gang of Four -- Design Patterns? I shall rewrite theirs implementation (albeit it is in C++) if you want to, but a little bit later.

This is one of those book you should have -- never know when it might come in handy.


For your requirement i think you should try Trove or Colt.These library's support primitive collections.


GNU Trove does something like that with the gnu.trove.decorator package (Map and Set only, not List).

This sort of thing is quite inefficient though, I doubt there are many situations where the trade-off is worth it.

Why not just use appropriate primitive collections?


I've made a test-program to see how well Flyweight would work in Java. For the record, I'll describe my results here. YMMV

1) If you have several fields in you objects, you will save some CPU by mashing them together in a single int or long. This is a pain to program and error prone, but it is a few percent faster, because multiple array access are more expensive than bit manipulation. More so as the number of fields grow.

2) For small instances (4 bytes of state) It will run about 25% slower then storing the instance directly. But, ONLY if you don't create a new instance on every get. This is where the real problem is. Having to create a new instance on every get is very expensive; in that case, it's not 25% slower, but 500% slower!

3) I see two way of saving the instance creation on get:

A) Your get method fills-in a pre-existing instance, instead of creating a new one. In other words, you pass a result object as input to your get method.

B) You use immutable instances, cache them, and return a cached instance from get. This is only useful if your list index is significant, and you expect to reuse the same values many times in your list. If you do this, then you may as well store directly a reference to your cached instance in your collection, instead of some state, because then you only pay the 4 bytes per instance for the reference anyway. In that case, your state would have to be 2 bytes or less before it made sense to store the state instead of a reference.

So, as final answer, the reason there is no general purpose library out there for Flyweight is that it only pays under specific conditions, otherwise it's not really worth it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜