[英]How to override method from the parent in multiple classes in the same way without creating class between parent and the child?
It's hard to properly ask, so I will create an example:很难正确地问,所以我将创建一个示例:
class Animal {
public void doSomething() {
}
}
class Dog extends Animal {
}
class Cat extends Animal {
}
class Sheltie extends Dog {
@Override
public void doSomething() {
super.doSomething();
System.out.println("Exactly the same");
}
}
class Abbysian extends Cat {
@Override
public void doSomething() {
super.doSomething();
System.out.println("Exactly the same");
}
}
Is there a way in this case that I can override the doSomething()
method in both Sheltie
and Abbysian
without duplicating a code and even typing @Override public void doSomething()
.在这种情况下,有没有一种方法可以覆盖Sheltie
和Abbysian
中的doSomething()
方法,而无需复制代码甚至键入@Override public void doSomething()
。 On top of that, I'd actually like to call super.doSomething()
as well.最重要的是,我实际上也想调用super.doSomething()
。 I cannot change inheritance at all.我根本无法更改 inheritance。
If those classes extended directly Animal
I would create a class "between" them.如果这些类直接扩展Animal
我会在它们“之间”创建一个 class 。 I was thinking of using interface
with default
method but that didn't help as well.我正在考虑将interface
与default
方法一起使用,但这也无济于事。
Once you broke out into Cats and Dogs you discovered the limitations of class hierarchy - eventually you'll hit a point of no return.一旦你闯入猫和狗,你就会发现 class 层次结构的局限性——最终你会遇到一个不归路。
Thankfully there is a thing called an Entity Component System (ECS) that is commonly used when you want to mish-mash functionality amongst many different entities.值得庆幸的是,当您想在许多不同的实体中混搭功能时,通常会使用一种称为实体组件系统 (ECS) 的东西。
A cat can wag its tail.猫可以摇尾巴。 A dog can wag its tail... but not all animals have tails.狗可以摇尾巴……但并非所有动物都有尾巴。 So you register a component called Tail to the tailed animal entities.因此,您将一个名为 Tail 的组件注册到有尾动物实体。
I found this on the StackExchange code review group.我在 StackExchange 代码审查小组中找到了这个。 https://codereview.stackexchange.com/questions/163215/entity-component-system-ecs https://codereview.stackexchange.com/questions/163215/entity-component-system-ecs
Decorator
pattern can do this trick but it would be applied to specific instances of Sheltie
/ Abyssinian
not to these classes: Decorator
模式可以做到这一点,但它会应用于Sheltie
/ Abyssinian
的特定实例而不是这些类:
class AnimalDecorator extends Animal {
protected Animal animal;
public AnimalDecorator(Animal animal) {
this.animal = animal;
}
@Override
public void doSomething() {
animal.doSomething(); // instead of call to super.doSomething
System.out.println("Exactly the same");
}
}
class Sheltie extends Dog { // doSomething not overridden
}
class Abyssinian extends Cat { // doSomething not overridden
}
// decorated instances
Animal sheltie = new AnimalDecorator(new Sheltie());
Animal abyssinian = new AnimalDecorator(new Abyssinian());
sheltie.doSomething();
abyssinian.doSomething();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.