1

我希望对特定设计提供一些帮助。这是我希望工作的代码:

abstract class Square {...}
abstract class Circle {...}

interface JPGExportable {...}

class SquareJPG extends Square implements JPGExportable {...}
class CircleJPG extends Circle implements JPGExportable {...}

interface Interface {
    draw(Square square);
    draw(Circle circle);
}

class Canvas implements Interface {
    draw(SquareJPG squarejpg) {...}
    draw(CircleJPG circlejpg) {...}
}

换句话说,Canvas 应该实现接口规范,但是绘图方法应该处理实现 JPGExportable 的 Square 和 Circle 的子类。

据我所知,有两种可行的解决方案,但我认为这两种解决方案都不是很漂亮:

/*
 * Using generics
 */
interface Interface<S extends Square, C extends Circle> {
    draw(S square);
    draw(C circle);
}

class Canvas implements Interface<SquareJPG, CircleJPG> {
    draw(SquareJPG squarejpg) {...}
    draw(CircleJPG circlejpg) {...}
}

/*
 * Using instanceof
 */
interface Interface {
    draw(S square);
    draw(C circle);
}

class Canvas implements Interface {
    draw(Square square) {
        if (square instanceof SquareJPG)
            // do stuff now
    }
    draw(Circle circle) {
        if (circle instanceof CircleJPG)
            // do stuff now
    }
}

实际上 Square 和 Circle 是相当不同的,为什么一个通用的超类不能包含任何通用代码。此外,实现 JPGExportable 的超类会感觉......错了;这确实是一个子功能。

我不喜欢泛型方式的一个根本原因是我需要处理 7 种不同的类型。也许我很挑剔,但是连续出现 7 次“T extends Type”看起来很难看。

  • 有没有看起来更好的第三种解决方案?
  • 如果不是,这两者中哪个“更好”?
4

1 回答 1

2

恕我直言,使用泛型更好,因为这样编译器可以为您提供一些静态类型检查。在第二种情况下,您会在运行时发现错误。

如果不查看其余代码,很难找到替代设计。即是否可以绘制任何 JPGExportable?也许你可以有一个只有一种方法draw(JPGEXportable)的接口?

于 2010-06-29T15:53:54.500 回答