gpt4 book ai didi

java - 策略模式中的通用方法重写

转载 作者:行者123 更新时间:2023-12-01 04:21:03 25 4
gpt4 key购买 nike

我必须做一些类似于粘贴的代码的事情,我有两个选择。类定义中包含泛型的一个(因此产生了一些警告)和以下一个。

由于类型删除,我无法使用后代的实现覆盖基本方法。

您认为这是一种正确且安全的方法吗?

public class Main {

public static void main(String args[]) {

List<Animal> animals = Arrays.asList(new Dog(), new Cat(), new Dog());
Map<Class<? extends Animal>, SoundPrinter> printers = new HashMap<Class<? extends Animal>, SoundPrinter>();
printers.put(Dog.class, new SoundDogPrinter());
printers.put(Cat.class, new SoundCatPrinter());

for (Animal animal:animals){
SoundPrinter printer = printers.get(animal.getClass());
System.out.println(printer.print(animal));
}
}
}

class Animal {

public String sound() {
return "animal sound";
}
}

class Dog extends Animal {

public String sound() {
return "dog sound";
}
}

class Cat extends Animal {

public String sound() {
return "cat sound";
}
}

abstract class SoundPrinter {

public <T extends Animal> String print(T animal) {
return "basic: " + animal.sound();
}
}

class SoundDogPrinter extends SoundPrinter {

public String print(Dog dog) {
return "dog's processed sound: " + dog.sound();
}
}

class SoundCatPrinter extends SoundPrinter {

public String print(Cat dog) {
return "cat's processed sound: " + dog.sound();
}
}

最佳答案

按照你的方式,print SoundDogPrinter中的方法和SoundCatPrinter不要覆盖printSoundPrinter .

类本身需要是通用的,而不是类中的方法。这样,print方法实际上会在 SoundDogPrinter 中被覆盖和SoundCatPrinter类。

abstract class SoundPrinter<T extends Animal> {

public String print(T animal) {
return "basic: " + animal.sound();
}
}

class SoundDogPrinter extends SoundPrinter<Dog> {

public String print(Dog dog) {
return "dog's processed sound: " + dog.sound();
}
}

class SoundCatPrinter extends SoundPrinter<Cat> {

public String print(Cat dog) {
return "cat's processed sound: " + dog.sound();
}
}

关于java - 策略模式中的通用方法重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18899864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com