Figure 20.1: Customer Class
Listing 20.1: Customer Class
class Customer {
public static final String US = "US";
public static final String CANADA = "Canada";
private String address;
private String name;
private String zip, state, type;
public boolean isValidAddress() {
…
…
}
public Customer(String inp_name, String inp_address,
String inp_zip, String inp_state,
String inp_type) {
name = inp_name;
address = inp_address;
zip = inp_zip;
state = inp_state;
type = inp_type;
}
}//end of class
不同的客户对象创建Customer对象并调用(invoke)isValidAddress方法验证客户地址的有效性。为了验证客户地址的有效性,Customer类期望利用一个地址验证类(address validator class),这个验证类提供了在接口AddressValidator中声明的接口。
Listing 20.2: AddressValidator as an Interface
public interface AddressValidator {
public boolean isValidAddress(String inp_address,
String inp_zip, String inp_state);
}//end of class
让我们定义一个USAddress的验证类,来验证给定的U.S地址。
Listing 20.3: USAddress Class
class USAddress implements AddressValidator {
public boolean isValidAddress(String inp_address,
String inp_zip, String inp_state) {
if (inp_address.trim().length() < 10)
return false;
if (inp_zip.trim().length() < 5)
return false;
if (inp_zip.trim().length() > 10)
return false;
if (inp_state.trim().length() != 2)
return false;
return true;
}
}//end of class