SE450: Flyweighting a factory: Keeping object references unique [32/32] Previous pageContents

It is sometimes an irritation to have more than one copy of an immutable object.

If we only had one copy of each object, for example, we could use == instead of equals.

This is sometimes refered to as a hash cons, or hash consing (LISP terminology).

file:Data.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package flyweight;
import java.util.HashMap;

public class Data {
  private Data() {}
  private static HashMap<Integer,Video> hashmap = new HashMap<Integer,Video>();

  private static int hash3 (Object key1, Object key2, Object key3) {
    return key1.hashCode () + 5 * key2.hashCode () + 13 * key3.hashCode ();
  }

  /**
   * Creates and manages flyweight objects. Ensures that flyweights
   * are shared properly.  When a client requests a flyweight, the
   * Flyweight Factory object supplies an existing instance or
   * creates one, if none exists.
   */
  static public Video getVideo(String title, int year, String director) {
    if (  (title == null)
        || (director == null)
        || (year <= 1800)
        || (year >= 5000)) {
      throw new IllegalArgumentException();
    }
    title = title.trim();
    director = director.trim();
    if (  ("".equals(title))
        || ("".equals(director))) {
      throw new IllegalArgumentException();
    }
    Integer key = hash3(title, year, director);
    Video v = hashmap.get(key);
    if (   (v == null)
        || !(v.title().equals(title))
        || (v.year() != year)
        || !(v.title().equals(title))) {
      v = new VideoObj(title, year, director);
      hashmap.put(key, v);
    }
    return v;
  }
}

Previous pageContents