Java – change classes and objects (other aproachs?)
I have several situations that I want to do This may be an example:
Consider the possible implementation of the chess game We define the abstract class' piece 'and the classes inherited from it:' Bishop 'peon' tower 'horse' Queen 'and so on
We may let our peon reach the end of the chessboard, and we may need a method to call the peon object to change the class of the object to "Queen", "horse" or anything else
So my question is, is there any way to do this in C or Java? If not, in other languages? In addition, is there any other way in this case?
Solution
You can use decorator pattern or strategy pattern
Decorated:
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; } }
Replace the pawn instance with a decorative instance when necessary So it still involves replacing an instance with another instance mentioned in the opensause's answer
ChessPiece pawn = new Pawn; ... pawn = new Decorated(pawn);
When you plan ahead, you can use a policy that still doesn't really change the class:
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(); } }