【问题标题】:Decorator Pattern, decorating subclasses that contain different methods装饰器模式,装饰包含不同方法的子类
【发布时间】:2014-12-29 02:41:18
【问题描述】:

假设我有一个Animal 抽象类和三个类DogCatBear,它们扩展了Animal 类。 Animal 类有抽象方法 getDescriptionDog 类有一个方法 getNumberOfHomeworksEaten,但 CatBear 没有。假设我有一个装饰器YellowStripesBlueStripesGreenStripes,它们都扩展了Animal 类并装饰了getDescription 方法。如果我用装饰器装饰 DogCatBear

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

如何访问doggetNumberOfHomeworksEaten 方法?在每个装饰器中都有getNumberOfHomeworksEaten 是没有意义的,因为CatBear 没有那个方法。

【问题讨论】:

    标签: java inheritance design-patterns decorator


    【解决方案1】:

    如果您将dog 转换为Dog,您将能够使用此方法。

    Animal animal = new Dog();
    animal = YellowStripes(animal);
    animal = BlueStripes(animal);
    animal = GreenStripes(animal);
    
    Dog dog = (Dog) animal;
    dog.getNumberOfHomeworksEaten();
    

    【讨论】:

    • 旁注:在您的示例中,所有装饰器都必须扩展Dog,否则您最终会得到ClassCastException
    • 我不明白为什么这个答案被接受,因为正如@home 评论的那样,这种方法完全破坏了装饰器的全部意义。有了这个“解决方案”,应该为每个子类创建一个装饰器类。
    猜你喜欢
    • 2020-01-11
    • 2014-01-14
    • 2011-06-26
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 2011-06-18
    • 2012-01-28
    • 1970-01-01
    相关资源
    最近更新 更多