1 package org.apidesign.apifest08.currency;
3 import java.lang.ref.WeakReference;
4 import java.math.BigDecimal;
5 import java.util.Currency;
7 import java.util.WeakHashMap;
11 * Create convertors using a flyweight to reduce the number of repetative creations of the same convertor.
13 * @author D'Arcy Smith
16 public final class ConvertorFactory
19 * flyweight so that only one vestion of each converter is created at a time.
21 private final static Map<String, WeakReference<Convertor>> convertors;
25 convertors = new WeakHashMap<String, WeakReference<Convertor>>();
29 * Prevent accidental construction.
31 private ConvertorFactory()
36 * Get the convertor for the specified currencies. The currency name format
37 * must be acceptable to java.util.Currency.getInstance(String)
39 * @param a the currency to convert from.
40 * @param aRate the exchange rate for a to b.
41 * @param b the currency to convert to.
42 * @param bRate the echante rate for b to a.
43 * @return the convertor for the specified currencies.
44 * @throws IllegalArgumentException if any of the arguments are null.
46 public static Convertor getConvertor(final String a,
47 final BigDecimal aRate,
49 final BigDecimal bRate)
51 final Currency currencyA;
52 final Currency currencyB;
53 final Convertor convertor;
55 currencyA = Currency.getInstance(a);
56 currencyB = Currency.getInstance(b);
57 convertor = getConvertor(currencyA, aRate, currencyB, bRate);
63 * Get the convertor for the specified currencies.
65 * @param a the currency to convert from.
66 * @param aRate the exchange rate for a to b.
67 * @param b the currency to convert to.
68 * @param bRate the echante rate for b to a.
69 * @return the convertor for the specified currencies.
70 * @throws IllegalArgumentException if either any of the arguments are null or if either rate <= 0.
72 public static Convertor getConvertor(final Currency a,
73 final BigDecimal aRate,
75 final BigDecimal bRate)
82 throw new IllegalArgumentException("a cannot be null");
87 throw new IllegalArgumentException("b cannot be null");
92 throw new IllegalArgumentException("aRate cannot be null");
97 throw new IllegalArgumentException("bRate cannot be null");
100 key = a.getCurrencyCode() + aRate + b.getCurrencyCode() + bRate;
102 // make sure that we don't try to overwrite one
103 synchronized(convertors)
105 if(!(convertors.containsKey(key)))
107 convertor = new ConvertorImpl(a, aRate, b, bRate);
108 convertors.put(key, new WeakReference(convertor));
112 convertor = convertors.get(key).get();