The composite pattern/entity system and traditional OOP

前端 未结 4 843
無奈伤痛
無奈伤痛 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:27

    I think you are using a wrong approach here. Patterns are supposed to be adopted to fit your needs, not vice versa. Simple is always better than complex, and if you feel that something does not work right, this means you should go a few steps back and perhaps start from the very beginning.

    For me, this has a code smell already:

    BaseEntity Alien = new BaseEntity();
    Alien.addComponent(new Position(), new AlienAIMovement(), new RenderAlien(), new ScriptAlien(), new Target());
    

    I would expect Object oriented code for that to look something like this:

    Alien alien = new AlienBuilder()
        .withPosition(10, 248)
        .withTargetStrategy(TargetStrategy.CLOSEST)
        .build();
    
    //somewhere in the main loop
    Renderer renderer = getRenderer();
    renderer.render(alien);
    

    When you use generic classes for all your entities, you will have a very generic and hard to use API for dealing with your objects.

    Besides, it feels wrong to have things like Position, Movement, and Renderer under the same Component umbrella. Position is not a component, it's an attribute. Movement is a behavior, and Renderer is something which is not related to your domain model at all, it's a part of graphics subsystem. Component could be a wheel for a car, body parts and guns for an alien.

    Game development a very sophisticated thing and it's really hard to make it right from the first attempt. Rewrite your code from scratch, learn from your mistakes and feel what you are doing, not just try to tailor a pattern from some article. And if you want to get better at patterns, you should try something else than game development. Write a simple text editor for instance.

提交回复
热议问题