سؤال

I have objects called "hierarchies", basically just a list of strings, eg. [1 2 3 4]. I also have objects called FormattedHierarchies that should always keep a formatted version of the hierarchy in the way the user wants them represented, e.g. (1-4) or {1,2,3,4}.

My problem is this:

I want to update the FormattedHierarchy immediately when the Hierarchy has been changed (e.g. if the Hierarchy changes from [1 2 3 4] to [1 2 3] the FormattedHierarchy should change from (1-4) to (1-3)).

Googling turned up the http://docs.oracle.com/javase/tutorial/uiswing/events/changelistener.html but my problem is this: if I want to have Hierarchy implement the ChangeListener, it has to implement the method "stateChanged".

The type Hierarchy must implement the inherited abstract method ChangeListener.stateChanged(ChangeEvent)

Having the Hierarchy create a new FormattedHierarchy is not feasible and I'm also thinking that this is not good class design. This is because the Hierarchy would then implement stuff that deals with its formatting (albeit in an indirect way).

Are there any standard or clever solutions to this problem?

هل كانت مفيدة؟

المحلول

I would try to avoid the need to have two objects kept exactly in sync. I can suggest you three ways:

  1. Have whoever is calling the Hierarchy setter call also a refresh() method on FormattedHierarchy. This is easy if you call the setter from one or really few places.
  2. Recalculate the String representation of Hierarchy only on demand, without storing it. You need to store the format, not the actual formatted result.
  3. Have Hierarchy maintain a version count, which is incremented every time you change it. FormattedHierarchy holds the formatted string, and the last version count it has seen. When you ask FormattedHierarchy for the string, it first checks if the version count has changed, triggering a recalc of the formatted string if case it did.

نصائح أخرى

Can't you simply merge Hierarchy class with FormattedHierarchy, using if needed two distinct Interfaces for your distinct consumers?

By this way, you would only have to create specific setters in your class that will modify both strings [1 2 3 4] and (1-4) to [1 2 3] and (1-3) when a set is done.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top