From 145f524f19b3d61cd12441c2f1a8de05d7dcfe60 Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Wed, 16 Oct 2019 12:31:09 -0400 Subject: Created the new BaseUnit, Unit and AbstractUnit implementations. --- src/org/unitConverter/newUnits/AbstractUnit.java | 76 ++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/org/unitConverter/newUnits/AbstractUnit.java (limited to 'src/org/unitConverter/newUnits/AbstractUnit.java') 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 . + */ +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 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; + } +} -- cgit v1.2.3