de.softmetz.commons.ddd.shared.vo.AbstractSingleValueObjectWithoutMappedValue.java Source code

Java tutorial

Introduction

Here is the source code for de.softmetz.commons.ddd.shared.vo.AbstractSingleValueObjectWithoutMappedValue.java

Source

/*
 *  commons-ddd is a set of Java classes for use in Domain Driven Design.
 *  Copyright (C) 2013  Christian Kalkhoff <softmetz@fsfe.org>
 *
 *  This file is part of commons-ddd.
 *
 *  commons-ddd is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  commons-ddd 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with commons-ddd.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.softmetz.commons.ddd.shared.vo;

import java.io.Serializable;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

/**
 * Abstract base class for value objects that consist of exactly one attribute.
 *
 * The abstract method getValue must be overriden to return the stored value. If you don't have special requirements to
 * the mapping of the value use {@link AbstractSingleValueObject}.
 *
 * Any subclass should implement an own getter to access the stored value(s).
 *
 * @param <T> Type of the encapsulated value
 * @param <VO> Type of the concrete implementation class
 * @author softmetz
 */
public abstract class AbstractSingleValueObjectWithoutMappedValue<T extends Serializable, VO extends AbstractSingleValueObjectWithoutMappedValue<T, VO>>
        extends AbstractValueObject<VO> {

    /**
     * @return The encapsulated value
     */
    protected abstract T getValue();

    @Override
    public boolean sameValueAs(VO other) {
        if (other == null) {
            return false;
        }
        return getValue().equals(other.getValue());
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(getValue()).hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (!getClass().isAssignableFrom(obj.getClass())) {
            return false;
        }
        return sameValueAs((VO) obj);
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this).append("value", getValue()).toString();
    }
}