1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/task1/solution04/src/org/apidesign/apifest08/currency/ConvertorFactory.java Sun Sep 28 14:12:38 2008 +0200
1.3 @@ -0,0 +1,95 @@
1.4 +package org.apidesign.apifest08.currency;
1.5 +
1.6 +import java.lang.ref.WeakReference;
1.7 +import java.util.Currency;
1.8 +import java.util.Map;
1.9 +import java.util.WeakHashMap;
1.10 +
1.11 +
1.12 +/**
1.13 + * Create convertors using a flyweight to reduce the number of repetative creations of the same convertor.
1.14 + *
1.15 + * @author D'Arcy Smith
1.16 + * @version 1.0
1.17 + */
1.18 +public final class ConvertorFactory
1.19 +{
1.20 + /**
1.21 + * flyweight so that only one vestion of each converter is created at a time.
1.22 + */
1.23 + private final static Map<String, WeakReference<Convertor>> convertors;
1.24 +
1.25 + static
1.26 + {
1.27 + convertors = new WeakHashMap<String, WeakReference<Convertor>>();
1.28 + }
1.29 +
1.30 + /**
1.31 + * Prevent accidental construction.
1.32 + */
1.33 + private ConvertorFactory()
1.34 + {
1.35 + }
1.36 +
1.37 + /**
1.38 + * Get the convertor for the specified currencies. The currency name format
1.39 + * must be acceptable to java.util.Currency.getInstance(String)
1.40 + *
1.41 + * @param a the currency to convert from.
1.42 + * @param b the currency to convert to.
1.43 + * @return the convertor for the specified currencies.
1.44 + */
1.45 + public static Convertor getConvertor(final String a,
1.46 + final String b)
1.47 + {
1.48 + final Currency currencyA;
1.49 + final Currency currencyB;
1.50 + final Convertor convertor;
1.51 +
1.52 + currencyA = Currency.getInstance(a);
1.53 + currencyB = Currency.getInstance(b);
1.54 + convertor = getConvertor(currencyA, currencyB);
1.55 +
1.56 + return (convertor);
1.57 + }
1.58 +
1.59 + /**
1.60 + * Get the convertor for the specified currencies.
1.61 + *
1.62 + * @param a the currency to convert from.
1.63 + * @param b the currency to convert to.
1.64 + * @return the convertor for the specified currencies.
1.65 + */
1.66 + public static Convertor getConvertor(final Currency a,
1.67 + final Currency b)
1.68 + {
1.69 + final String key;
1.70 + Convertor convertor;
1.71 +
1.72 + if(a == null)
1.73 + {
1.74 + throw new IllegalArgumentException("a cannot be null");
1.75 + }
1.76 +
1.77 + if(b == null)
1.78 + {
1.79 + throw new IllegalArgumentException("b cannot be null");
1.80 + }
1.81 +
1.82 + key = a.getCurrencyCode() + b.getCurrencyCode();
1.83 +
1.84 + // make sure that we don't try to overwrite one
1.85 + synchronized(convertors)
1.86 + {
1.87 + if(!(convertors.containsKey(key)))
1.88 + {
1.89 + convertor = new Convertor(a, b);
1.90 + convertors.put(key, new WeakReference(convertor));
1.91 + }
1.92 + }
1.93 +
1.94 + convertor = convertors.get(key).get();
1.95 +
1.96 + return (convertor);
1.97 + }
1.98 +}