Search code examples
c++design-patternshierarchyobserver-pattern

What Design Pattern to use?


The problem to model is this:

A hierarchy of levels within an Army, starting with the national army in whole, through field armies, subunits, and eventually the individual men. Each level may involve links to one or more other classes such as General or Officer or whatever. The units within say a field army need to be able to communicate with each other, especially for purposes of modeling morale, cohesion, etc, as well as with those of any enemy field army (e.g. a unit routing in my army affects the enemy morale positively). Furthermore, each unit needs to communicate with those above and below it in the hierarchy (for obvious purposes).

I was thinking of having the links in the physical hierarchy represented by actual pointers (possibly bilateral) in each of these entities' classes (e.g. army* in each unit and unit* or a whole collection of them in each army) and then making use of the observer design pattern to implement any communication in other cases (such as the case I mentioned above).

However, being no expert in design patterns or programming for that matter I do not know whether there is any other more efficient manner to do this. Any help would be greatly appreciated.


Solution

  • There is a model/design pattern for communicating events between disparate entities that may not know of eachothers existence before the communication happens. The pattern is called 'Publish/Subscribe'.

    Each entity sends events it wants to publish to a broker and tells the broker about what kinds of events it would be interested in. The broker handles making sure the subscribing entities learn of events they find interesting that are published.

    This is like the Observer pattern, but in the Observer pattern each interested entity subscribes individually to each entity it wants events from. I think this could result in a lot of overhead because that requires everybody to care about creation and destruction of things.

    Anyway, there is a nice Wikipedia article on Publish/Subscribe.

    I would use the Composite pattern (which basically means a tree of some form) for the individual armies. And possibly Observer for relationships up and down the hierarchy or with siblings. But Observer requires too much registering and unregistering for it to be workable in the general case.