A good architecture / design pattern for giving multiple shared attributes in different combinations

architectural-patternsArchitecturedesigndesign-patternsobject-oriented

I have a need for many different objects to have various combinations of attributes. For a demonstrative example, a flaming dog would have a dog attribute, a flame attribute, and a tail attribute, while a water cat will share the exact same tail attribute but have its own water and cat attributes, which it also shares with others, etc. Each attribute has complex behaviors and completely unique methods that I would want to store in a class for each, and there will be many different combinations of these for each of the various objects.

I then need to be able to count up the number of each attribute constituted in the current application, and then use the unique methods within each represented class based on the number. In the above example, I would use the flame attributes unique methods with value 1, but the tail methods with value 2.

Is there a good architecture for organizing these attributes on each of the objects? My first thought is to just give, for example, each flaming dog a member variable for each of type flame, tail and dog. Then I can iterate across all objects and count up repeated attributes, and access the methods on any of them with the final tally. But with this, I will have many unused attribute objects which are only instantiated to end up in a count, and otherwise completely redundant.

I could also have all of the attributes be singletons and have the objects hold a reference to them, but then I would always have to have all of the many attributes instantiated at all times and handled as globals so that I can have their attributes at the ready to be pointed to, which also feels like overkill and wasteful in its own way.

Is there some design pattern or architecture that accomplishes a more efficient way to handle this? Sorry for what is probably a fairly common question, but I wasn't sure how to search for an answer to this without typing up this whole essay.

Best Answer

Yes there is. It is called the entity component system. It is used mostly in gaming industry to avoid deep hierarchies and share "components" (attributes or behavior or both) between "entity" objects dynamically, preferring composition over inheritance.

Related Topic