I'm having a problem understanding decorator design pattern. Let's say I want to use it in my project. It is a platform game so I immediately thought the best usage would be on enemy classes. I would like to have different types of enemies, the basic one and the others that would be extensions of the first one (e.g with different attributes, colours, additional AI logic). From my understanding this is how classes should look like
abstract class Enemy{
float speedX,speedY;
int x,y,width,height;
COLOR colour;
Sprite sprite;
void setAnimation();
void update();
void render();
void init();
}
class EnemyBasic extends Enemy{
EnemyBasic() {
init();
}
void init() {
//set all variables
}
@Override
void setAnimation() {
//set animation
}
@Override
public void update() {
//update
}
@Override
public void render() {
render(sprite,colour,x,y,width,height)
}
}
class FastEnemy extends Enemy{
Enemy basicEnemy;
FastEnemy(Enemy basicEnemy) {
this.basicEnemy = basicEnemy;
init();
}
void init() {
basicEnemy.init();
maximalSpeed = basicEnemy.maximalSpeed*2;
}
@Override
void setAnimation() {
basicEnemy.setAnimation();
}
@Override
public void update() {
basicEnemy.update();
additionalMovementLogic();
}
additionalMovementLogic(){
}
@Override
public void render() {
color=green;
basicEnemy.render()
}
}
The problem is, this wouldn't work because methods calls from basicEnemy
object would operate on EnemyBasic fields and not those from EnemyFast.So for example render() would render EnemyBasic object and not EnemyFast. Only solution that I can see is to reimplement the whole class but what is the point of decorator class then? Am I understanding something wrong ? Or in this case decorator shouldn't be used ? And if so when it should be used
Aucun commentaire:
Enregistrer un commentaire