1
我会喜欢一些特定设计的帮助。这是祝工作代码:实现特定接口并具有特定超类的参数:泛型或instanceof?
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) {...}
}
在口头上,画布应该实现的接口规范,但平局的方法应该实现JPGExportable正方形和圆形的只有柄的子类。
据我所知,有两种解决方案的工作,但没有我想的是很漂亮:
/*
* 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
}
}
在现实正方形和圆形是相当明显的,为什么一个普通超一流的不会是能够包含任何通用的代码。另外,一个实现JPGExportable的超类会感觉错误;它真的是一个子功能。
我不喜欢泛型方式的根本原因是我需要处理7种不同的类型。也许我很挑剔,但连续出现7次“T extends Type”看起来很丑。
- 是否有第三种解决方案看起来更好?
- 如果不是,那两个“哪个更好”?
感谢您的回复! 不,JPGExportable并不意味着可绘制(这可能是什么让这一点更难)。因此,使用draw(JPGExportable)的界面看起来很奇怪,并不能真正反映界面的内容。 – eferm 2010-06-29 16:22:19