All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.seedstack.business.specification.AndSpecification Maven / Gradle / Ivy

/*
 * Copyright © 2013-2024, The SeedStack authors 
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package org.seedstack.business.specification;

/**
 * A specification composing multiple specifications with a logical AND.
 *
 * @param  the type of the candidate object the specification applies to.
 */
public class AndSpecification implements Specification {

    private final Specification[] specifications;

    /**
     * Creates a specification composing the specifications passed as argument with a logical AND.
     *
     * @param specifications the specifications to compose in a logical AND.
     */
    @SafeVarargs
    public AndSpecification(Specification... specifications) {
        this.specifications = specifications.clone();
    }

    @Override
    public boolean isSatisfiedBy(T candidate) {
        for (Specification specification : specifications) {
            if (!specification.isSatisfiedBy(candidate)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < specifications.length; i++) {
            Specification term = specifications[i];
            boolean isNegation = term instanceof NotSpecification;
            if (!isNegation) {
                sb.append("(");
            }
            sb.append(term.toString());
            if (!isNegation) {
                sb.append(")");
            }
            if (i < specifications.length - 1) {
                sb.append(" ∧ ");
            }
        }
        return sb.toString();
    }

    /**
     * Returns the composed specifications.
     *
     * @return the array of specifications composed with the logical AND.
     */
    public Specification[] getSpecifications() {
        return specifications.clone();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy