lundi 13 juin 2016

Is there a better alternative for the following OOP design?

I have a collection of classes, call them Derived1, Derived2, ..., Derived6, each of which is a subclass of a base class Base. These classes are defined in a third-party Java package.

I'm writing a class that will write out a human-readable representations of these objects. I approached the problem as following: define methods String transform(Derivedi object), for each i=1,2,...,6, and String transform(Base object).

The problem occurs when, for example, Base obj = new Derived3(...) and I want to compute the representation for obj. The expression transform(obj) invokes the method with signature String transform(Base), which has to call the "right" method (in this case the one with the signature String transform(Derived3)).

The method String transform(Base object) delegates work to the appropriate method via a sequence of conditional statements of the form if (obj instanceof Derivedi) for each i=1,2,...,6. (If I had control over the package I would have an abstract method String toReadable() on the base class, which every derived class would have to implement; unfortunately in this case I have no control over the package.)

I don't like this solution (it's easy to see why). What would be the alternatives to this implementation of String transform(Base)?

Aucun commentaire:

Enregistrer un commentaire