1

我正在尝试实现一个“Range”类(在 Java 中)为它包装的 int 值提供边界强制功能。我希望它的每个子类都定义自己的最小/最大界限,而不必重写执行这些界限的逻辑。这是一个例子:

public abstract class Range {
    // I would like each derived class to possess its own distinct instances of the
    // min/max member data
    protected static final int MIN_VAL;
    protected static final int MAX_VAL;

    protected int _value;

    public void set (int newVal) {
        // Range check the input parameter
        // this should use the min/max bounds for the object's most derived class
        if (newVal < MIN_VAL || newVal > MAX_VAL) {
            throw new InvalidParameterException("`newVal` is out of range");
        }

        this._value = newVal;
    }

    public int get() {
        return this._value;
    }
}

// This class should limit its wrapped value to values between 1 and 6 inclusively
public class Die extends Range {
    public Die() {
        MIN_VAL = 1;
        MAX_VAL = 6;
        this.set (1);
    }
}

显然这个实现不起作用,但我怎样才能实现我的目标呢?在不重复大部分逻辑的情况下这是否可能?

4

2 回答 2

3

一种方法是创建最小值/最大值实例变量,并让您的子类在构造函数中设置范围:

public abstract class Range {
    // I would like each derived class to possess its own distinct instances of the
    // min/max member data
    protected final int MIN_VAL;
    protected final int MAX_VAL;

    protected int _value;

    protected Range(int min, int max) {
        MIN_VAL = min;
        MAX_VAL = max;
    }

    . . .
}

// This class should limit its wrapped value to values between 1 and 6 inclusively
public class Die extends Range {
    public Die() {
        super(1, 6);
        . . .
    }
}

另一种方法是定义一个抽象checkRange方法:

public abstract class Range {
    protected int _value;

    public void set (int newVal) {
        checkRange(newVal);
        this._value = newVal;
    }

    public int get() {
        return this._value;
    }

    protected abstract void checkRange(int val) throws InvalidParameterException;
}

// This class should limit its wrapped value to values between 1 and 6 inclusively
public class Die extends Range {
    private final int MIN_VAL = 1;
    private final int MAX_VAL = 6;
    public Die() {
        this.set (1);
    }

    protected void checkRange(int val) throws InvalidParamterException {
        if (newVal < MIN_VAL || newVal > MAX_VAL) {
            throw new InvalidParameterException("`val` is out of range");
        }
    }
}
于 2012-12-30T17:22:34.177 回答
1

MIN_VAL 和 MAX_VAL 是常量,因此您无法更改它们。

添加两个受保护的方法:

protected abstract int getMin();

protected abstract int getMax();

子类实现这些方法,例如:

@Override
protected int getMin() {
   return 7;
}

@Override
protected int getMax() {
   return 67;
}

在 Range 你然后改变

public void set (int newVal) {
        // Range check the input parameter
        // this should use the min/max bounds for the object's most derived class
        if (newVal < getMin() || newVal > getMax()) {
            throw new InvalidParameterException("`newVal` is out of range");
        }

        this._value = newVal;
    }
于 2012-12-30T17:24:07.893 回答