mardi 4 août 2015

Pattern Matching like behavior

I am at a lookout for a design pattern for my simple problem. Here is a simplified version.

class Animal{...}
class Dog extends Animal{...}
class Cat extends Animal{...}
... //so on, 3 other classes as of now

I have a static method (in reality exposed via web-service but its synonymous) which takes an id and returns an animal.

If a cat is returned then the other team using the cat object generates a CatReport. If Dog, then dog report (They can use it for anything). Obviously Cat & Dog have different attributes. Cat and Dog dont have anything else in common apart from the fact that they are Animals. So making a call like below, is insufficient because I need to the precise type:

public static Animal getAnimal(int id){}

Not sufficient because animal does not contain all the information what the precise type can give me.

What is the best way to deal with this problem?


PS: In Scala, I would simply do pattern-matching on the object. This solves the problem elegantly.

One solution I have is: make a call which returns an enum signifying what the id corresponds to. And then have separate call for each:

public static AnimalType getAnimalType(int id){}
public static Cat getCat(int id){}
public static Dog getDog(int id){}
....

But this is cumbersome.

Aucun commentaire:

Enregistrer un commentaire