Designing a connection between related classes

I need help developing a problem:

There are 3 classes Map, Road and City:

1.class HAS Map-List of roads and list of cities

2.class Road has 2 cities - d and s.

3. Class City HAS-List of Roads

I need to design a function to add and remove a path to \ from the map, while it should be elegant and safe.

elegant - smallest code and more efficient

safe - all relevant variable classes should be aware of adding / removing.

notification: if you create a method for any of the classes that do not notify other change classes, it can be called and destroy the database.

The idea I did was this:

have a method for each of the classes:

Map: addRoad (City d, City), which creates a new Road (City d, City s), adds it to its list and Runs applyRoad ()

Road: applyRoad (), which calls d.addRoad (this) and s.addRoad (this)

City: addRoad (Road r) adds the road to the list of roads for a specific city instance

The problem with the one who wondered is that adding roads is only correct if the encoder uses Map.addRoad (), there will be no synchronization in the database in any other way. (you can call road.applyRoad (), and then the list of maps will not be synchronized with the change)

+4
source share
1 answer

Plectrum scheme suitable:

http://en.wikipedia.org/wiki/Mediator_pattern

The mediator knows about everyone. And he solves the problem through communication.


NB: Looking at a sample observer who seemed like a good candidate, this is not so, because:

  • good: modularity: subject and observers can vary independently.
  • good: extensibility: can define and add any number of observers
  • good: customizability: different observers provide different types of theme
  • Bad: unexpected updates: observers do not know about each other
  • Bad: upgrade overhead: prompts may be required

source: http://en.wikibooks.org/wiki/Java_Programming/Design_Patterns#Observer

+1
source

Source: https://habr.com/ru/post/1397046/


All Articles