Java-子类验证设计模式 [英] Java - subclass validation design pattern

查看:100
本文介绍了Java-子类验证设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基类为 C ,字段为 X Y Z

I am having a base class C with fields X, Y and Z.

C1 扩展了 C 并有一个额外的字段, T

C1 extends C and is having an extra field, T.

C1 构造函数中,确实使用字段 X 的一些硬编码值调用超级( C )构造函数Y Z 。然后设置 T

In the C1 constructor, I do call the super (C) constructor with some hard coded values for the fields X, Y and Z. Then I set T.

是否有任何模式可以自动验证的所有字段C1 通过在 C 构造函数中执行某些操作?因此,我试图将自动验证推向基类。

Are there any patterns to automatically validate all the fields of C1 by doing something in the C constructor ? So I am trying to push the automatic validation to the base class.

请注意,调用超级构造函数应该在中的任何语句之前完成C1 构造函数。我从一些抽象的 validate()方法开始,但是我不是正确的人。

Please note that calling the super constructor should be done before any statement in the C1 constructor. I started with some abstract validate() method, but I am not I am on the right track.

谢谢

推荐答案

我会说,超类应该进行自我验证。对象需要执行自己的合同。 C值的任何验证都应在其自己的构造函数中进行。

I would say that the super class should validate itself. An object needs to enforce its own contract. Any validation of C's values should be done in its own constructor. Likewise, the subclass should validate itself.

public class A {
    private int x;

    public A(int x) {
        if (x < 0) throw new IllegalArgumentException("x cannot be negative");
        this.x = x;
    }
}

public class B extends A {
    private String y;

    public B(int x, String y) {
        super(x);
        if (y == null) throw new IllegalArgumentException("y cannot be null");
        this.y = y;
    }
}

这篇关于Java-子类验证设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆