- 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
让我们定义一个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
USAddress类实现AddressValidator接口,因此Customer对象使用USAddress实例作为验证客户地址过程的一部分是没有任何问题的。
Listing 20.4: Customer Class Using the USAddress Class
- class Customer {
- …
- …
- public boolean isValidAddress() {
- //get an appropriate address validator
- AddressValidator validator = getValidator(type);
- //Polymorphic call to validate the address
- return validator.isValidAddress(address, zip, state);
- }
- private AddressValidator getValidator(String custType) {
- AddressValidator validator = null;
- if (custType.equals(Customer.US)) {
- validator = new USAddress();
- }
- return validator;
- }
- }//end of class