Can be used to create an internal pool of objects so a factory does not hand out duplicates. This works in a manner similar to the String.intern() method and is useful for optimizing memory use.
/**
* Please note that Foo must be *immutable* and have *equals/hashcode* defined.
*/
class FooFactory {
public Foo create(String definition) {
Foo created = new Foo(definition);
return (Foo) canionicalSet.unique(created);
}
}
At a technical level this class is an AbstractSet in which the entries are weak references. This means that CanonicalSet will not hold onto created objects when they are no longer in active use by your application.
Is this not a Cache?
Nope - its use is different. We are optimizing for memory use here rather than speed.