task4/solution02/src/org/apidesign/apifest08/currency/CompositeConvertor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 11 Oct 2008 23:38:46 +0200
changeset 61 58ec6da75f6f
parent 45 task3/solution02/src/org/apidesign/apifest08/currency/CompositeConvertor.java@251d0ed461fb
permissions -rw-r--r--
Copying structure for task4
     1 package org.apidesign.apifest08.currency;
     2 
     3 import java.io.Serializable;
     4 import java.util.Arrays;
     5 import java.util.Currency;
     6 
     7 /**
     8  * Convertor that is composed from other convertors. 
     9  * @author lukas
    10  *
    11  */
    12 class CompositeConvertor implements ExtendedConvertor, Serializable {
    13 
    14 	private static final long serialVersionUID = -2702026568249130055L;
    15 	
    16 	private final ExtendedConvertor[] convertors;
    17 
    18 
    19 	public CompositeConvertor(ExtendedConvertor... convertors) {
    20 		this.convertors = convertors.clone();
    21 		for (ExtendedConvertor convertor: this.convertors)
    22 		{
    23 			if (convertor==null)
    24 			{
    25 				throw new NullPointerException("One of the convertors to be merged is null");
    26 			}
    27 		}
    28 	}
    29 
    30 	/**
    31 	 * Returns true if the composite contains convertor that supports given conversion.
    32 	 */
    33 	public boolean isConversionSupported(Currency from, Currency to) {
    34 		return findConvertorFor(from, to)!=null;
    35 	}
    36 
    37 
    38 	/**
    39 	 * If the composite contains convertor that supports given conversion, delegates to its convert method.
    40 	 * Throws {@link IllegalArgumentException} convertor supporting given conversion is not found. 
    41 	 */
    42 	public Money convert(Money amount, Currency destinationCurrency) throws IllegalArgumentException {
    43 		ExtendedConvertor convertor = findConvertorFor(amount.getCurrency(), destinationCurrency);
    44 		if (convertor!=null)
    45 		{
    46 			return convertor.convert(amount, destinationCurrency);
    47 		}
    48 		throw new IllegalArgumentException("Conversion not supported. Can not convert to "+destinationCurrency+".");
    49 	}
    50 	
    51 	/**
    52 	 * Finds convertor for given currencies. If not found, returns null. 
    53 	 * @param from
    54 	 * @param to
    55 	 * @return
    56 	 */
    57 	ExtendedConvertor findConvertorFor(Currency from, Currency to) {
    58 		//does linear search, in the future can cache the results.
    59 		for (ExtendedConvertor convertor:convertors)
    60 		{
    61 			if (convertor.isConversionSupported(from, to))
    62 			{
    63 				return convertor;
    64 			}
    65 		}
    66 		return null;
    67 	}
    68 	
    69 
    70 	@Override
    71 	public String toString() {
    72 		return getClass().getName()+" converts "+Arrays.toString(convertors);
    73 	}
    74 
    75 }