java - 处理 bean 类中的自定义限制/异常?

标签 java design-patterns custom-data-type

我在我的应用程序中为自定义数据类型创建了一些自定义 bean 类,例如 Address , PhoneNumber , SpecialCode

这些自定义的非原始数据类型 有自己的限制,我想对它们应用这些限制,例如考虑 PhoneNumber :

public class PhoneNumber {
   private String stdCode;
   private String number;

   public PhoneNumber() {
   }

   public PhoneNumber(String stdCode, String number) {

      this.stdCode = stdCode;
      this.number = number;
   }

   /* getters and setters */

}

现在让我感到困惑的是 PhoneNumber 上的限制 ,即,我想确保 stdCode必须以 0 开头,或 number必须是 78数字长等 那么,这些规则应该在哪里应用呢?
在构造函数中?作为:

//Custom costructor
public PhoneNumber(String stdCode, String number) {
    if (!stdCode.matches("[0-9]+") || !number.matches("[0-9]+")){
        throw new IllegalArgumentException("Error in Parsing. The STD Code and Number MUST be numeric digits.");
    }
    if (!"0".equals(stdCode.substring(1, 2))){
        throw new IllegalArgumentException("The STD Code must begins with 0");
    }
    if (stdCode.length() < 3 || stdCode.length() > 5){
        throw new IllegalArgumentException("The STD Code must be 3 to 5 digits long. Current Number of digits: " + stdCode.length() + ". ");
    }
    this.stdCode = stdCode;
    this.number = number;
}

或者也可以有自定义异常(exception)?我应该在哪里将这些自定义异常与我的 bean 类合并?
我不是一个经验丰富的程序员,想知道我应该在这里应用什么设计模式?

最佳答案

你应该为你的手机 # 部分创建 getters 和 setters 并在 setters 中验证检查

关于java - 处理 bean 类中的自定义限制/异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10804250/

相关文章:

c++ - 在 C++ 中自动更新新结构中的相关值

MySQL 列数据类型接受时间或单词列表

ruby-on-rails - 使用特定于数据库的数据类型进行 Rails 迁移

JavaMail API 将附件作为转发邮件发送给发件人

java - 在java中查找pgm文件中二维数组的平均值

java - 我可以生成复杂度 < O(n^2) 的所有子字符串吗

java - 在 AWS、Azure 之间切换。设计模式

java - 如何用Java打印Trie树?

java - 为对象动态添加属性的设计模式

model-view-controller - MVC 模式中的 Controller 和 MVP 模式中的演示者有什么区别?