使用观察者模式是否合适?

发布于 2024-10-03 00:35:43 字数 855 浏览 1 评论 0原文

支持 我有一个严格保存实例字段的 Java Bean 类:

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

假设对于 College 实例中的每个更改,都会发送一条消息:

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

假设我有一个 Swing GUI (Java),它也检查 College 中的更改

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

是观察者模式相关吗?如果大学有 1000 个变量,那么每当实例字段值发生变化时,我就必须包含一个“notifyObservers()”方法!

例如,对于这 1000 个变量,我有 1000 个 setter 方法。每个 setter 方法都必须有一个 notificationObservers() 调用。

这是正确的还是有更好的方法?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

长亭外,古道边 2024-10-10 00:35:43

如果您有一个包含 1000 个字段的类,您可能会遇到其他更相关的设计问题。

每个字段更改方法(setter)调用 notifyObservers() 并不是异常。您可能想尝试封装尽可能多的状态和逻辑;信息隐藏只是一个很好的设计。

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.

女皇必胜 2024-10-10 00:35:43

我认为 Observer 在这里还可以,但是 Listener 更好,因为
1. 可以创建多种类型的监听器
2. 当事件发生时,它被传递给监听器的处理方法,这样它就可以知道到底发生了什么。例如,它可能包含 Mark 评论中提到的 1000 个字段之一。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文