特定のデザインに関するヘルプがあれば幸いです。これは私が働きたいコードです:
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 は Interface という仕様を実装する必要がありますが、描画メソッドはJPGExportable を実装する Square と Circle のサブクラスのみを処理する必要があります。
私の知る限り、機能する解決策は 2 つありますが、どちらもあまりきれいではないと思います。
/*
* 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 つの異なる型を処理する必要があるからです。私がうるさいのかもしれませんが、「T extends Type」が 7 回連続して出現するのは見栄えが悪いです。
- 見栄えの良い 3 番目のソリューションはありますか?
- そうでない場合、どちらが「より良い」ですか?