What is “loose coupling?” Please provide examples

2019-01-03 04:10发布

I can't seem to grok the concept of "loose coupling." I suppose it doesn't help that the word "loose" usually has a negative connotation, so I always forget that loose coupling is a good thing.

Will somebody please show some "before" and "after" code (or pseudocode) that illustrates this concept?

20条回答
▲ chillily
2楼-- · 2019-01-03 04:37

Coupling refers to how tightly different classes are connected to one another. Tightly coupled classes contain a high number of interactions and dependencies.

Loosely coupled classes are the opposite in that their dependencies on one another are kept to a minimum and instead rely on the well-defined public interfaces of each other.

Legos, the toys that SNAP together would be considered loosely coupled because you can just snap the pieces together and build whatever system you want to. However, a jigsaw puzzle has pieces that are TIGHTLY coupled. You can’t take a piece from one jigsaw puzzle (system) and snap it into a different puzzle, because the system (puzzle) is very dependent on the very specific pieces that were built specific to that particular “design”. The legos are built in a more generic fashion so that they can be used in your Lego House, or in my Lego Alien Man.

Reference: https://megocode3.wordpress.com/2008/02/14/coupling-and-cohesion/

查看更多
We Are One
3楼-- · 2019-01-03 04:38

In simple language, loosely coupled means it doesn’t depend on other event to occur. It executes independently.

查看更多
登录 后发表回答