Java 装饰器模式,装饰包含不同方法的子类
假设我有一个Java 装饰器模式,装饰包含不同方法的子类,java,inheritance,design-patterns,decorator,Java,Inheritance,Design Patterns,Decorator,假设我有一个Animal抽象类和三个类Dog、Cat、和Bear,它们扩展了Animal类Animal类具有抽象方法getDescriptionDog类有一个方法GetNumberOfHomeworkseat,但是Cat和Bear没有。假设我有一个decoratorsYellowStripes,BlueStripes,GreenStripes,它们都扩展了Animal类并装饰了getDescription方法。如果我用装饰师装饰狗、猫和熊: Animal dog = new Dog(); dog
Animal
抽象类和三个类Dog
、Cat
、和Bear
,它们扩展了Animal
类Animal
类具有抽象方法getDescription
Dog
类有一个方法GetNumberOfHomeworkseat
,但是Cat
和Bear
没有。假设我有一个decoratorsYellowStripes
,BlueStripes
,GreenStripes
,它们都扩展了Animal
类并装饰了getDescription
方法。如果我用装饰师装饰狗、猫和熊:
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
的getnumberofhomeworkseat
方法?在每个装饰器中都要吃getnumberofhomeworks
是没有意义的,因为Cat
和Bear
没有那种方法。如果你把dog
投给dog
你就可以使用这种方法了
Animal animal = new Dog();
animal = YellowStripes(animal);
animal = BlueStripes(animal);
animal = GreenStripes(animal);
Dog dog = (Dog) animal;
dog.getNumberOfHomeworksEaten();
旁注:在您的示例中,所有装饰器都必须扩展
Dog
,否则您将陷入ClassCastException
。