001package flyweight;
002import java.util.HashMap;
003
004public class Data {
005        private Data() {}
006        private static HashMap<Integer,Video> hashmap = new HashMap<Integer,Video>();
007
008        private static int hash3 (Object key1, Object key2, Object key3) {
009                return key1.hashCode () + 5 * key2.hashCode () + 13 * key3.hashCode ();
010        }
011
012        /**
013         * Creates and manages flyweight objects. Ensures that flyweights
014         * are shared properly.  When a client requests a flyweight, the
015         * Flyweight Factory object supplies an existing instance or
016         * creates one, if none exists.
017         */
018        static public Video getVideo(String title, int year, String director) {
019                if (  (title == null)
020                                || (director == null)
021                                || (year <= 1800)
022                                || (year >= 5000)) {
023                        throw new IllegalArgumentException();
024                }
025                title = title.trim();
026                director = director.trim();
027                if (  ("".equals(title))
028                                || ("".equals(director))) {
029                        throw new IllegalArgumentException();
030                }
031                Integer key = hash3(title, year, director);
032                Video v = hashmap.get(key);
033                if (   (v == null)
034                                || !(v.title().equals(title))
035                                || (v.year() != year)
036                                || !(v.title().equals(title))) {
037                        v = new VideoObj(title, year, director);
038                        hashmap.put(key, v);
039                }
040                return v;
041        }
042}
043