The composite pattern/entity system and traditional OOP

随声附和 提交于 2020-01-11 17:43:09

问题


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/Entity system (which I originally read about here and here) as an alternative to typical deep hierarchical inheritance.

Now, after writing several thousand lines of code, I'm a bit confused. I think understand the pattern and I enjoy using it. I think it's very cool and Starbucks-ish, but it feels that the benefit it provides is somewhat short-lived and (what irks me most) heavily dependent on your granularity.

Here's a picture from the second article above:

I love the way objects (Game entities, or whatever you want to call them) have a minimal set of components and the inferred idea is that you could write code that looks something like:

BaseEntity Alien = new BaseEntity();
BaseEntity Player = new BaseEntity();

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

.. which would be really nice... but in REALITY, the code ends up looking something like

BaseEntity Alien = new BaseEntity();
BaseEntity Player = new BaseEntity();

Alien.addComponent(new Position(), new AlienAIMovement(), new RenderAlien(), new ScriptAlien(), new Target());
Player.addComponent(new Position(), new KeyboardInputMovement(), new RenderPlayer(), new ScriptPlayer(), new PhysicsPlayer());

It seems that I end up having some very specialized components that are made up of lesser components. Often times, I have to make some components that have dependencies of other components. After all, how can you render if you have no position? Not only that, but the way you end up rendering a player vs. an alien vs. a grenade can be fundamentally different. You can't have ONE component that dictates all three, unless you make a very big component (in which case... why are you using the composite pattern anyway?)

To give another real-life example. I have characters in my game that can equip various gear. When a piece of gear is equipped, some statistics are changed as well as what's displayed visually. Here's what my code looks like right now:

billy.addControllers(new Movement(), new Position(), new CharacterAnimationRender(), new KeyboardCharacterInput());

billy.get(CharacterAnimationRender.class).setBody(BODY.NORMAL_BODY);
billy.get(CharacterAnimationRender.class).setFace(FACE.BLUSH_FACE);
billy.get(CharacterAnimationRender.class).setHair(HAIR.RED_HAIR);
billy.get(CharacterAnimationRender.class).setDress(DRESS.DRAGON_PLATE_ARMOR);

The above CharacterAnimationRender.class only affects what's displayed VISUALLY. So I clearly need to make another Component that handles gear stats. However, why would I do something like:

billy.addControllers(new CharacterStatistics());

billy.get(CharacterAnimationRender.class).setBody(BODY.NORMAL_BODY);
billy.get(CharacterStatistics.class).setBodyStats(BODY_STATS.NORMAL_BODY);

When I can just make a CharacterGearStuff controller/component that handles BOTH the distribution of stats as well as the visual change?

Bottom line, I'm not sure how this is supposed to help productivity since unless you want to handle everything manually, you still have to create "meta-components" that depend on 2+ components (and modify/cross-modify all of their sub-components - bringing us back to OOP). Or maybe I'm thinking about it completely wrong. Am I?


回答1:


It sounds like you've slightly misunderstood the component pattern.

Components are data ONLY, no code. If you have code in your component, it's not a component any more - it's something more complex.

So, for instance, you should be able to trivially share your CharacterAnimationRender and CharacterStatistics, e.g.:

CharacterStats { int BODY }
CharacterGameStats { ...not sure what data you have that affects gameplay, but NOT the rendering... }
CharacterVisualDetails { int FACE, int HAIR }

...but there is no need for these to be aware of the existence of each other. The moment you talk about "dependencies" between components, I suspet you've got lost. How can one struct of ints "depend upon" another struct of ints? They can't. They're just chunks of data.

...

Going back to your concerns at the start, that you end up with:

Alien.addComponent(new Position(), new AlienAIMovement(), new RenderAlien(), new ScriptAlien(), new Target());
Player.addComponent(new Position(), new KeyboardInputMovement(), new RenderPlayer(), new ScriptPlayer(), new PhysicsPlayer());

...that's perfect. ASSUMING you've written those components correctly, you've split out the data into small chunks that are easy to read/debug/edit/code against.

However, this is making guesses because you haven't specified what's inside those components ... e.g. AlienAIMovement - what's in that? Normally, I'd expect you to have a "AIMovement()", and then edit it to make it into an Alien's version, e.g. change some internal flags in that component to indiate it's using the "Alien" functions in your AI system.




回答2:


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.




回答3:


Ents seems to be designed to do exactly what you want. If you still want your own library, you could at least learn from its design.

The previous answers all seem clunky and create tons of unnecessary objects, IMO.




回答4:


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.



来源:https://stackoverflow.com/questions/4941953/the-composite-pattern-entity-system-and-traditional-oop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!