1 package org.apidesign.apifest08.currency;
3 import java.lang.ref.WeakReference;
4 import java.util.Currency;
6 import java.util.WeakHashMap;
10 * Create convertors using a flyweight to reduce the number of repetative creations of the same convertor.
12 * @author D'Arcy Smith
15 public final class ConvertorFactory
18 * flyweight so that only one vestion of each converter is created at a time.
20 private final static Map<String, WeakReference<Convertor>> convertors;
24 convertors = new WeakHashMap<String, WeakReference<Convertor>>();
28 * Prevent accidental construction.
30 private ConvertorFactory()
35 * Get the convertor for the specified currencies. The currency name format
36 * must be acceptable to java.util.Currency.getInstance(String)
38 * @param a the currency to convert from.
39 * @param b the currency to convert to.
40 * @return the convertor for the specified currencies.
42 public static Convertor getConvertor(final String a,
45 final Currency currencyA;
46 final Currency currencyB;
47 final Convertor convertor;
49 currencyA = Currency.getInstance(a);
50 currencyB = Currency.getInstance(b);
51 convertor = getConvertor(currencyA, currencyB);
57 * Get the convertor for the specified currencies.
59 * @param a the currency to convert from.
60 * @param b the currency to convert to.
61 * @return the convertor for the specified currencies.
63 public static Convertor getConvertor(final Currency a,
71 throw new IllegalArgumentException("a cannot be null");
76 throw new IllegalArgumentException("b cannot be null");
79 key = a.getCurrencyCode() + b.getCurrencyCode();
81 // make sure that we don't try to overwrite one
82 synchronized(convertors)
84 if(!(convertors.containsKey(key)))
86 convertor = new Convertor(a, b);
87 convertors.put(key, new WeakReference(convertor));
91 convertor = convertors.get(key).get();