diff -r 251d0ed461fb -r 58ec6da75f6f task4/solution02/src/org/apidesign/apifest08/currency/CompositeConvertor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/task4/solution02/src/org/apidesign/apifest08/currency/CompositeConvertor.java Sat Oct 11 23:38:46 2008 +0200 @@ -0,0 +1,75 @@ +package org.apidesign.apifest08.currency; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Currency; + +/** + * Convertor that is composed from other convertors. + * @author lukas + * + */ +class CompositeConvertor implements ExtendedConvertor, Serializable { + + private static final long serialVersionUID = -2702026568249130055L; + + private final ExtendedConvertor[] convertors; + + + public CompositeConvertor(ExtendedConvertor... convertors) { + this.convertors = convertors.clone(); + for (ExtendedConvertor convertor: this.convertors) + { + if (convertor==null) + { + throw new NullPointerException("One of the convertors to be merged is null"); + } + } + } + + /** + * Returns true if the composite contains convertor that supports given conversion. + */ + public boolean isConversionSupported(Currency from, Currency to) { + return findConvertorFor(from, to)!=null; + } + + + /** + * If the composite contains convertor that supports given conversion, delegates to its convert method. + * Throws {@link IllegalArgumentException} convertor supporting given conversion is not found. + */ + public Money convert(Money amount, Currency destinationCurrency) throws IllegalArgumentException { + ExtendedConvertor convertor = findConvertorFor(amount.getCurrency(), destinationCurrency); + if (convertor!=null) + { + return convertor.convert(amount, destinationCurrency); + } + throw new IllegalArgumentException("Conversion not supported. Can not convert to "+destinationCurrency+"."); + } + + /** + * Finds convertor for given currencies. If not found, returns null. + * @param from + * @param to + * @return + */ + ExtendedConvertor findConvertorFor(Currency from, Currency to) { + //does linear search, in the future can cache the results. + for (ExtendedConvertor convertor:convertors) + { + if (convertor.isConversionSupported(from, to)) + { + return convertor; + } + } + return null; + } + + + @Override + public String toString() { + return getClass().getName()+" converts "+Arrays.toString(convertors); + } + +}