Reputation: 8580
i need help in a designing issue:
there are 3 classes Map,Road and City :
1.class Map HAS-A List of Roads and List of Cities
2.class Road has 2 Cities - d and s.
3.class City HAS-A List of Roads
i need to Design the function of adding and removing a road to\from the map, while it needs to be elegant and safe.
elegant - least code and better efficiency
safe - all relevant classes variables must be aware of the addition\removal.
notice: if you make a method on any of the classes that doesnt notify other classes of the change, it might get invoked and ruine the database.
the idea i had of doing it was as following :
have a method for each of the classes :
Map : addRoad(City d,City s) which creates a new Road(City d,City s) add it to its List and Runs applyRoad()
Road : applyRoad() which invokes d.addRoad(this) and s.addRoad(this)
City : addRoad(Road r) adds road to the list of roads of the specific city instance
the problem with that to whoever wondered is that addition of roads is being done correctly only if the coder uses Map.addRoad(), in any other way, there will be a lack of sychronization in database. (one can invoke road.applyRoad() and then Map's list will not be synchronized with the change)
Upvotes: 4
Views: 111
Reputation: 5010
The mediator pattern is appropriate:
http://en.wikipedia.org/wiki/Mediator_pattern
The mediator knows about everyone. And it resolves your issue with coupling.
NB: After looking at the observer pattern which seemed a good candidate, it's a no go because:
source: http://en.wikibooks.org/wiki/Java_Programming/Design_Patterns#Observer
Upvotes: 1