summaryrefslogtreecommitdiff
path: root/src/org/unitConverter/newUnits/AbstractUnit.java
blob: bc4608e58a1a90ff0928e1fe32b2fcd7ae53e8bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
 * Copyright (C) 2019 Adrien Hopkins
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package org.unitConverter.newUnits;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.unitConverter.dimension.BaseDimension;
import org.unitConverter.math.ObjectProduct;

/**
 * @author Adrien Hopkins
 * @since 2019-10-16
 */
public abstract class AbstractUnit implements Unit {
	/**
	 * The combination of units that this unit is based on.
	 */
	private final ObjectProduct<BaseUnit> unitBase;

	/**
	 * Cache storing the result of getDimension()
	 */
	private transient ObjectProduct<BaseDimension> dimension = null;

	/**
	 * Creates the {@code AbstractUnit}.
	 * 
	 * @param unitBase
	 * @since 2019-10-16
	 * @throws NullPointerException
	 *             if unitBase is null
	 */
	public AbstractUnit(final ObjectProduct<BaseUnit> unitBase) {
		this.unitBase = Objects.requireNonNull(unitBase, "unitBase must not be null.");
	}

	/**
	 * @return unitBase
	 * @since 2019-10-16
	 */
	@Override
	public final ObjectProduct<BaseUnit> getBase() {
		return this.unitBase;
	}

	@Override
	public final ObjectProduct<BaseDimension> getDimension() {
		if (this.dimension == null) {
			final Map<BaseUnit, Integer> mapping = this.unitBase.exponentMap();
			final Map<BaseDimension, Integer> dimensionMap = new HashMap<>();

			for (final BaseUnit key : mapping.keySet()) {
				dimensionMap.put(key.getBaseDimension(), mapping.get(key));
			}

			this.dimension = ObjectProduct.fromExponentMapping(dimensionMap);
		}
		return this.dimension;
	}

	@Override
	public String toString() {
		return "Unit derived from base " + this.getBase().toString();
	}
}