例:
public class Date {
private int Day;
private String Month;
private int Year;
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能这样做,一旦设置了日期,可能的日期值可能只有1到31个月和从1月到12月,并且只接受这些值.
由于字段是私有的,您可以检查设置者的有效性.例如:
public void setMonth(int month) {
if (month < 1 || month > 12) {
throw new IllegalArgumentException(month + " is not a valid month. Month must be between 1 and 12 inclusive";
}
this.month = month;
}
Run Code Online (Sandbox Code Playgroud)
另一种模式是构建器模式,它有几种风格,包括:
public Date withMonth(int month) {
if (month < 1 || month > 12) {
throw new IllegalArgumentException(month + " is not a valid month. Month must be between 1 and 12 inclusive";
}
this.month = month;
return this;
}
Run Code Online (Sandbox Code Playgroud)
以上具有在一行中创建对象的优点:
Date myDate = new Date().withMonth(6).withDate(6).withYear(1976);
Run Code Online (Sandbox Code Playgroud)
另一方面,通常使用小写字母启动变量名称并使用驼峰套管.类名称将以大写字母开头,常量(枚举和静态韵母)应全部用大写字母表示,以提高可读性.
| 归档时间: |
|
| 查看次数: |
358 次 |
| 最近记录: |