0

Support I have a Java Bean class that strictly holds instance fields:

class College 
{
     building = "Burruss";
     dean = "Mr. Bergess";
     schools[] String = {"College of Engineering", "Business School"};
     valedictorian = "Mr. Smart Guy";
     ...
     ...
     ...
}

Suppose that for every change in an instance of College, a message is sent:

class messageSender
{
       ... if (College values have changed)
              Send that instance's fields in byte[] form
}

Suppose that I have a Swing GUI (Java) that also checks for changes in College

class myGUI
{
      ... if (College values have changed)
              Alert each individual JTextField the updated field
}

Is the observer pattern relevant here? If college had 1000 variables, I would then have to include a "notifyObservers()" method for every time the instance fields values changes!

For example, for those 1000 variables, I have 1000 setter methods. Each setter method must then have a notifyObservers() call.

Is this right or is there a better way?

2 Answers2

2

If you have a class with 1000 fields, you probably have other, more pertinent design problems.

It is not abnormal for each of your field-altering methods (setters) to call notifyObservers(). You may want to try encapsulating as much state and logic as you can though; information hiding is just good design.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
  • Please describe more "pertinent design problems" for a class with 1000 fields. A class strictly for holding data is unsafe? –  Nov 16 '10 at 21:18
  • 1
    @Carlo: No, I have confidence Java could handle it. It's just very rare that even a simple bean should have that many properties. It's usually an indication that some normalization or at least further division into other classes would be useful. – Mark Peters Nov 16 '10 at 21:21
0

I think that Observer is OK here, but Listener is better because 1. you can create several types of listeners 2. when event happens it is passed to handler method of listener, so it can know what really happened. For example it may contain one of 1000 fields mentioned in Mark's comment.

AlexR
  • 114,158
  • 16
  • 130
  • 208