0

我目前正在从事一个面向对象的设计项目,并且想知道是否有更好的方法来验证子类的变异器中的数据。

例如,我有一个 Home 类,其中包含子类 Apartment、Condo 和 House。在 Home 类中,我想包含子类共享的(私有)字段的修改器。假设其中一个字段是 squareFootage。有没有办法使 Home 中的 mutator 足够通用,以便子类可以为 squareFootage 设置自己的有效值,而不必完全覆盖 mutator?也就是说,我希望每个子类的 squareFootage 有不同的有效范围。

我尝试在 Home 中设置可能的范围值,然后在子类中覆盖它们。不幸的是, Home 中的 mutator 仍然从 Home 类而不是子类中获取。

因此,我采用了对突变体进行抽象的方法,但不幸的是,这会导致大量重复代码,因为我可以从字面上复制和粘贴每个子类中的突变体。

如果可能的话,我想让可能的范围值保持静态,我知道这可能通过反射来实现,但我真的很想避免在这个项目中使用它。

4

3 回答 3

1

I think is possible by adding an abstract "validator" method that have to be implemented in the subclasses, something like this:

public class Home {

    private float squareFootage;

    public abstract void validateSquareFootage() throws MyValidationException; // you could throw an exception, runtime exception or return a boolean to indicate if value is valid or not

    public void setSquareFootage(float squareFootage) {
        validateSquareFootage(squareFootage); // again, throws exception or returns boolean, up to you
        this.squareFootage = squareFootage;
    }

    // ... rest of implementation
}

And in a subclase:

public class Condo extends Home {

    @Override
    public void validateSquareFootage(float squareFootage) throws MyValidationException {
        // ... do validations
    }

}

and you don't have to override the mutator at all, just implement the correct validator.

于 2013-07-30T02:18:43.850 回答
0

If I understood your problem correctly, I think you want something like this ?

abstract class Home<T>{
    protected T squareFootage;
    abstract void setSquareFootage(T t);
}

class Apartment extends Home<String>{
    @Override void setSquareFootage(String t) {
        //...do something about the parameter
        this.squareFootage = t;
    }
}

class Condo extends Home<Integer>{
    @Override void setSquareFootage(Integer t) {
        //...do something about the parameter
        this.squareFootage = t;
    }
}

class House extends Home<Boolean>{
    @Override void setSquareFootage(Boolean t) {
        //...do something about the parameter
        this.squareFootage = t;
    }
}
于 2013-07-30T02:12:14.520 回答
0

最好使 Home 类成为一个抽象类,并在您的子类中扩展它。这样,您可以在主类中创建适用于所有子类的方法,但您可以在子类中覆盖它们

于 2013-07-30T02:00:12.937 回答