The composite pattern/entity system and traditional OOP

前端 未结 4 828
無奈伤痛
無奈伤痛 2021-02-01 06:42

I\'m working on a small game written in Java (but the question is language-agnostic). Since I wanted to explore various design patterns, I got hung up on the Composite pattern/E

4条回答
  •  时光说笑
    2021-02-01 07:18

    David,

    first thank you for your perfect question.

    I understand your problem and think that you did not use the pattern correctly. Please read this article: http://en.wikipedia.org/wiki/Composite_pattern

    If for example you cannot implement general class Movement and need AlienAIMovement and KeyboardMovement you probably should use Visitor pattern. But before your are starting refactoring of thousands of code lines check whether you can do the following.

    Is it a chance to write class Movement that accepts parameter of type BaseEntity? Probably the difference between all implementations of Movement is just a parameter, flag or so? In this case your code will look like:

    Alien.addComponent(new Position(), new Movement(Alien), new Render(Alien), new Script(Alien), new Target());

    I think it is not so bad.

    If it is not possible, try to create instances using factory, so

    Alien.addComponent(f.createPosition(), f.createMovement(Alien), f.createRender(Alien), f.createRenderScript(Alien), f.createTarget());

    I hope my suggestions help.

提交回复
热议问题