开发者

Is it appropriate to use the Observer Pattern?

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

class College 
{
     building = "Burruss";
     dean = "Mr. Bergess";
     schools[] String = {"开发者_Go百科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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜