Decorator Pattern, decorating subclasses that contain different methods

Suppose I have an abstract class Animal

and three classes Dog

, Cat

and Bear

that extend the class Animal

. Animal

the class has an abstract method getDescription

. Dog

class has a method getNumberOfHomeworksEaten

, but Cat

and Bear

do not. Suppose that I have decorators YellowStripes

, BlueStripes

, GreenStripes

that extend the class Animal

and decorate method getDescription

. If I decorate Dog

, Cat

and with Bear

decorators:

Animal dog = new Dog();
dog = YellowStripes(dog);
dog = BlueStripes(dog);
dog = GreenStripes(dog);

Cat cat = new Cat();
//decorate cat

Bear bear = new Bear();
//decorate bear

      

How do I access the method getNumberOfHomeworksEaten

for Dog

? It would be pointless to have getNumberOfHomeworksEaten

each decorator since Cat

and Bear

do not have this method.

+3


source to share


1 answer


If you cast dog

in dog

, you should be able to use this method.



Animal animal = new Dog();
animal = YellowStripes(animal);
animal = BlueStripes(animal);
animal = GreenStripes(animal);

Dog dog = (Dog) animal;
dog.getNumberOfHomeworksEaten();

      

+1


source







All Articles