samedi 24 octobre 2015

What OOD pattern to use when it looks like you need to access a subclass method via a superclass reference?

I'm working on a problem similar to this: there are Offices and Districts. Some, but not all, Offices have sales information. Some, but not all, Districts have sales information. Offices that have sales information are always in Districts that have sales information, and they require that district sales information. Offices that don't have sales information, don't care what kind of district they are in. So, how does one best model this in object oriented design?

Obviously, we have Office and District classes, and there is a relationship between the two. The most straightforward implementation is to include sales information members directly in these classes and those members are null when sales information isn't present. However, it seems more OO to me to partition out instances with sales information as instances of SalesOffice and SalesDistrict and so you would have something like this:

District <-------- Office
    ^                 ^
    |                 |
SalesDistrict      SalesOffice
  * GetSalesInfo     * GetSalesInfo

Here's the rub: SalesOffice.GetSalesInfo needs to call SalesDistrict.GeSalesInfo, and casting District to SalesDistrict just seems like a bad idea.

There must be a commonly used design pattern that can be applied here so that:

  1. An Office can always know what District it belongs to, regardless of what kind of district it is.
  2. A subset of offices and districts have sales information.
  3. An Office with sales information can access the sales information of the District it belongs to.

Suggestions? Should I just forget about inheritance and create an IsSalesType flag for both Office and District or is there a better way?

Aucun commentaire:

Enregistrer un commentaire