diff options
Diffstat (limited to 'src/org/unitConverter/newUnits/AbstractUnit.java')
-rw-r--r-- | src/org/unitConverter/newUnits/AbstractUnit.java | 76 |
1 files changed, 76 insertions, 0 deletions
diff --git a/src/org/unitConverter/newUnits/AbstractUnit.java b/src/org/unitConverter/newUnits/AbstractUnit.java new file mode 100644 index 0000000..909ea8b --- /dev/null +++ b/src/org/unitConverter/newUnits/AbstractUnit.java @@ -0,0 +1,76 @@ +/** + * 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 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; + } +} |