/** * 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 . */ 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 unitBase; /** * Cache storing the result of getDimension() */ private transient ObjectProduct dimension = null; /** * Creates the {@code AbstractUnit}. * * @param unitBase * @since 2019-10-16 * @throws NullPointerException * if unitBase is null */ public AbstractUnit(final ObjectProduct unitBase) { this.unitBase = Objects.requireNonNull(unitBase, "unitBase must not be null."); } /** * @return unitBase * @since 2019-10-16 */ @Override public final ObjectProduct getBase() { return this.unitBase; } @Override public final ObjectProduct getDimension() { if (this.dimension == null) { final Map mapping = this.unitBase.exponentMap(); final Map 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(); } }