2014-11-02 3 views
3

가정하자 다른 방법을 포함 장식 서브 클래스는 내가 가진 Animal 추상 클래스와 세 개의 클래스 Dog, CatAnimal 클래스를 확장 Bear. Animal 클래스에는 추상 메서드 getDescription이 있습니다. Dog 클래스는 getNumberOfHomeworksEaten이지만, CatBear은 포함되어 있지 않습니다. YellowStripes, BlueStripes, GreenStripes이 모두 Animal 클래스를 확장하고 getDescription 메서드를 장식한다고 가정합니다. 나는 장식과 Dog, CatBear을 장식하는 경우 :데코레이터 패턴,

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 
내가 dog에 대한 getNumberOfHomeworksEaten 방법에 액세스 할 수있는 방법을

? CatBear에는 그 방법이 없기 때문에 각 장식 자에 getNumberOfHomeworksEaten을 갖는 것은 이치에 맞지 않습니다.

답변

1

dogDog으로 설정하면이 방법을 사용할 수 있습니다.

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

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

사이드 노트 : 모든 데코레이터는 'Dog'를 확장해야하며 그렇지 않으면'ClassCastException'으로 끝납니다. – home

관련 문제