0

I have a base Address class which defines basic address properties and acts as an CRUD object:

  • Name
  • Company
  • Address Line 1
  • Address Line 2
  • Address Line 3
  • City
  • State
  • Postal Code
  • Country

I have a 'ShipToAddress' class which extends Address and includes two more properties:

  • Phone Number
  • Email Address

Address includes validation methods for each of its properties, and ShipToAddress includes validation for only its properties (Phone Number and Email Address).

My issue is, I also want to account for both USA and International addresses for both of these classes without duplicating code, so that I can have different validation methods for State and Postal Code. USA State validation would ensure that the value is one of the 50 States. International validation would simply ensure that it does not exceed the length allowed in the database.

How can I design this to allow for any number of different types of addresses (USA, Canada, etc.) but also have the base Address class and the ShipToAddress class, without duplicating the code? I basically want the following:

  • Address Base Class
  • ShipToAddress
  • USAAddress
  • USAShipToAddress
  • ***Address
  • ***ShipToAddress
4

2 回答 2

5

将 AddressValidator 定义为单独的接口。

public interface AddressValidator {
    boolean validateAddress(ShipToAddress add);
}

创建它的不同实现 -USAAddressValidatorCanadaAddressValidator

你可以有一个根据国家Factory给你合适的AddressValidator对象。

public class AddressValidatorFactory {
    public static AddressValidator GetValidator(Address address) { ... }   
}

您还应该考虑是否ShipToAddress应该extend Addresscontain它。你要在预期的ShipToAddress地方传递对象吗?Address如果没有,则无需ShipToAddress扩展地址。

于 2012-10-22T17:34:28.157 回答
2

我可能会将其设为模板,并将验证器作为模板参数传递:

class US_validator { /* ... */ };

class Int_validator { /* .. */ };

template <class Validator>
class Address { 
   // ...
};

template <class Validator>
class Shipping_address  : public Address {
    // ...
};

typedef Address<US_validator> US_Address;
typedef Address<Int_validator> Int_Address;
typedef Shipping_address<US_validator> US_Shipping_address;
typedef Shipping_address<Int_validator> Int_Shipping_address;

另一种可能性是使用多重继承,将验证器作为基类。

class US_validator { /* ... */ };
class Int_validator { /* ... */ };

class Address { /* ... */ };
class Shipping_Address : public Address { /* ... */ };

class US_Shipping_Address : public US_validator, public Shipping_Address { /* ... */ };
class Int_Shipping_Address : public Int_validator, public Shipping_Address { /* ... */ };

后者的使用频率不高,也没有(可能)被大多数人认为是有利的,但仍然可以很好地工作。

于 2012-10-22T16:31:40.533 回答