01: /*
02: * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
03: * Copyright (C) 2006 - JScience (http://jscience.org/)
04: * All rights reserved.
05: *
06: * Permission to use, copy, modify, and distribute this software is
07: * freely granted, provided that this notice is preserved.
08: */
09: package javax.measure.converter;
10:
11: /**
12: * <p> This class represents a converter multiplying numeric values by a
13: * constant scaling factor (approximated as a <code>double</code>).
14: * For exact scaling conversions {@link RationalConverter} is preferred.</p>
15: *
16: * <p> Instances of this class are immutable.</p>
17: *
18: * @author <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a>
19: * @version 3.1, April 22, 2006
20: */
21: public final class MultiplyConverter extends UnitConverter {
22:
23: /**
24: * Holds the scale factor.
25: */
26: private final double _factor;
27:
28: /**
29: * Creates a multiply converter with the specified scale factor.
30: *
31: * @param factor the scale factor.
32: * @throws IllegalArgumentException if offset is one (or close to one).
33: */
34: public MultiplyConverter(double factor) {
35: if ((float) factor == 1.0)
36: throw new IllegalArgumentException(
37: "Identity converter not allowed");
38: _factor = factor;
39: }
40:
41: /**
42: * Returns the scale factor.
43: *
44: * @return the scale factor.
45: */
46: public double getFactor() {
47: return _factor;
48: }
49:
50: @Override
51: public UnitConverter inverse() {
52: return new MultiplyConverter(1.0 / _factor);
53: }
54:
55: @Override
56: public double convert(double amount) {
57: return _factor * amount;
58: }
59:
60: @Override
61: public boolean isLinear() {
62: return true;
63: }
64:
65: @Override
66: public UnitConverter concatenate(UnitConverter converter) {
67: if (converter instanceof MultiplyConverter) {
68: double factor = _factor
69: * ((MultiplyConverter) converter)._factor;
70: return valueOf(factor);
71: } else if (converter instanceof RationalConverter) {
72: double factor = _factor
73: * ((RationalConverter) converter).getDividend()
74: / ((RationalConverter) converter).getDivisor();
75: return valueOf(factor);
76: } else {
77: return super .concatenate(converter);
78: }
79: }
80:
81: private static UnitConverter valueOf(double factor) {
82: float asFloat = (float) factor;
83: return asFloat == 1.0f ? UnitConverter.IDENTITY
84: : new MultiplyConverter(factor);
85: }
86:
87: private static final long serialVersionUID = 1L;
88: }
|