I'm new in design patterns and now I am learning about Factory Method pattern. I try to make an example using animals.
I have an Animal interface with two methods, breathe and walk. Implementing this interface I have two classes, Giraffe and Flamingo.
Following the pattern I have two factories, one for Giraffes and one for Flamingos and a main class like this:
if (color.equals("yellow")) {
factory = new GiraffeFactory();
} else {
factory = new FlamingoFactory();
}
Animal animal = factory.createAnimal();
animal.breathe();
animal.walk();
This works perfectly but now I realise that Flamingos can fly. I don't want to include this method in Animal interface because Giraffes can't.
How can I call this new method only in Flamingo Animal instances? Is cast the only solution? Or is this pattern only for objects that has the same methods from their interface?
((Flamingo) animal).fly();
Thank you so much.
Aucun commentaire:
Enregistrer un commentaire