虱子耦合和 java 按钮

Louse coupling and java buttons

我正在看一本书,书中给出了一个松散耦合的例子:

As an example take Javas buttons, where you take and assign a button listener to the buttons of the existing type without having to change anything in the existing button class.

我不确定我是否理解作者的意思。这是松散耦合的一个例子吗?

耦合松散,因为 Button 对您的特定 ButtonListener 实现一无所知。相反,ButtonListener 对 Button 了解不多。 ButtonListener 接口只为您提供一个事件 - 封装您需要知道的有关更改内容的信息。您的实施在对该事件源类型的认识方面受到限制。因此,您的侦听器和按钮永远不会使用它们的 class 级 API 元素直接相互交谈,它们只会根据它们实现的接口(ButtonListener 和 Event)相互交谈。从广义上讲,当两个 classes 通过共享抽象 API 相互通信时,它们被描述为松散耦合 - 这意味着它们都不依赖于另一个的特定于实现的细节,因此它们内部结构可以独立更改。