您也许可以使用装饰器模式或策略模式。
带装饰器:
interface ChessPiece {
Set<Move> getPossibleMoves();
Image getAppearance();
}
class Pawn implements ChessPiece {
...
}
class Decorator implements ChessPiece {
ChessPiece decorated;
public Decorator(ChessPiece decorated_) {
this.decorated = decorated_;
}
@override
Set<Move> getPossibleMoves() {
Set<Move> result = decorated.getPossibleMoves();
// alter result
return result;
}
}
需要时,您将Pawn
实例替换为Decorated
实例。 因此,它仍然涉及用OpenSause 的回答中提到的另一个实例替换一个实例。
ChessPiece pawn = new Pawn;
...
pawn = new Decorated(pawn);
当您提前计划时,您可以使用 strategy它仍然没有真正改变类:
interface PossibleMovesStrategy {
Set<Move> getPossibleMoves();
}
interface AppearanceStrategy {
Image getAppearance();
}
class ChangingChessPiece extends ChessPiece {
PossibleMovesStrategy posMoves;
AppearanceStrategy appearance;
@override
Set<Move> getPossibleMoves() {
return posMoves.getPossibleMoves();
}
@override
Image getAppearance() {
return appearance.getAppearance();
}
}