UnaryConstraint.java

/* Copyright 2015 Laurent COCAULT
 * Licensed to Laurent COCAULT under one or more contributor license agreements.
 * See the NOTICE file distributed with this work for additional information
 * regarding copyright ownership. Laurent COCAULT licenses this file to You
 * under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License.  You may obtain a copy of the
 * License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.csp.constraint.model;

/**
 * Represents an unary constraint in a constraint solving problem. To define a
 * new unary constraint, inherit this class and define the propagate method.
 */
public abstract class UnaryConstraint<T> extends Constraint<T> {

    /**
     * An unary constraint is associated with only one variable.
     */
    private Variable<T> variable_;

    /**
     * Constructor of an unary constraint. It references the variable given as
     * parameters.
     * @param name
     *            Name of the binary constraint
     * @param variable
     *            Reference of the variable
     */
    public UnaryConstraint(final String name, final Variable<T> variable) {
        super(name);
        variable_ = variable;
    }

    /**
     * Get the variable associated with the constraint.
     * @return The reference of the variable associated with the constraint
     */
    public Variable<T> getVariable() {
        return variable_;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isBinary() {
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isTernary() {
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isUnary() {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isUnsized() {
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isVariableReferenced(final Variable<T> variable) {
        return variable_ == variable;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean revise() {
        try {
            // Propagate and check if the domain is empty
            if (isPropagationEnabled()) {
                propagate();
            }
            return !variable_.getDomain().isEmpty();
        } catch (EmptyDomainException e) {
            // If the domain has been emptied, return false
            return false;
        }
    }

}