【问题标题】:Generic methods overriding in Strategy pattern策略模式中覆盖的通用方法
【发布时间】:2013-09-19 16:12:46
【问题描述】:

我必须做一些类似于粘贴代码的事情,我有两个选择。在类定义中具有泛型的一个(结果有一些警告)和以下一个。

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

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

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();
    }
}

【问题讨论】:

  • 如果您在 Map&lt;Class&lt;? extends Animal&gt;, SoundPrinter&gt; 中对类进行硬编码,我看不出泛型添加了什么...
  • 我在这里看不到策略模式。你想达到什么目标?每只动物一台打印机?通用打印机?
  • @SotiriosDelimanolis SoundPrinter 应该是一个抽象基类,用于打印各种动物,而不仅仅是狗
  • @Chirs 是啊是啊,写得太快了。
  • @BoristheSpider 我需要泛型来打印基类 SoundPrinter。

标签: java generics overriding strategy-pattern


【解决方案1】:

按照您的方式,SoundDogPrinterSoundCatPrinter 中的 print 方法不会覆盖 SoundPrinter 中的 print

类本身需要是泛型的,而不是类中的方法。这样,print 方法实际上将在SoundDogPrinterSoundCatPrinter 类中被覆盖。

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();
    }
}

【讨论】:

  • 您还可能需要public abstract Class&lt;T&gt; myClass() 方法来返回事物映射到的类。这将使处理的映射对类是内生的......
  • @rgettman 这样我就会收到描述中提到的警告:Unchecked call to 'print(T)' as a member of raw type 'SoundPrinter'。
  • @BoristheSpider 确实,它使事情变得更加清晰,但它不影响主要问题,即上面显示的困境警告/“技巧”。通过此更改,它仅更改了添加到地图的内容:printers.put(catPrinter.prints(), catPrinter);
  • 我还不确定如何消除该警告。
猜你喜欢
  • 2011-05-11
  • 2011-06-19
  • 1970-01-01
  • 2021-11-16
  • 2018-02-05
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
  • 2016-12-22
相关资源
最近更新 更多