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
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
Figure 20.2: Customer/USAddress Validator?Class Association
Figure 20.3: Class Adapter for the CAAddress Class Listing 20.6: CAAddressAdapter as a Class Adapter
public class CAAddressAdapter extends CAAddress implements AddressValidator { public boolean isValidAddress(String inp_address, String inp_zip, String inp_state) { return isValidCanadianAddr(inp_address, inp_zip, inp_state); } }//end of class
在Customer类内部,getValidator私有方法需要扩展,以至于它可以在验证加拿大客户的时候返回一个CAAdressAdapter实例。返回的对象是多态的,USAddress和CAAddressAdapter都实现了AddressValidator接口,所以不用改变。 Listing 20.7: Customer Class Using the CAAddre