什么是“松耦合”?请提供示例

我似乎无法理解“松散耦合”的概念。我想这不利于单词“宽松”通常有负面的含义,所以我总是忘了松耦合是一个很好的事情。

有人可以显示说明此概念的“之前”和“之后”代码(或伪代码)吗?


12345678_0001
浏览 935回答 3
3回答

Qyouu

考虑一个简单的购物车应用程序,该应用程序使用CartContents类来跟踪购物车中的项目,并使用Order类来处理购买。订单需要确定购物车中内容的总价值,它可能会像这样:紧密耦合示例:public class CartEntry{&nbsp; &nbsp; public float Price;&nbsp; &nbsp; public int Quantity;}public class CartContents{&nbsp; &nbsp; public CartEntry[] items;}public class Order{&nbsp; &nbsp; private CartContents cart;&nbsp; &nbsp; private float salesTax;&nbsp; &nbsp; public Order(CartContents cart, float salesTax)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this.cart = cart;&nbsp; &nbsp; &nbsp; &nbsp; this.salesTax = salesTax;&nbsp; &nbsp; }&nbsp; &nbsp; public float OrderTotal()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; float cartTotal = 0;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < cart.items.Length; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cartTotal += cart.items[i].Price * cart.items[i].Quantity;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; cartTotal += cartTotal*salesTax;&nbsp; &nbsp; &nbsp; &nbsp; return cartTotal;&nbsp; &nbsp; }}注意OrderTotal方法(以及Order类)如何取决于CartContents和CartEntry类的实现细节。如果我们试图更改此逻辑以允许折扣,则可能必须更改所有三个类别。另外,如果我们更改为使用List集合来跟踪项目,则也必须更改Order类。现在,这是一种执行相同操作的更好方法:较少耦合的示例:public class CartEntry{&nbsp; &nbsp; public float Price;&nbsp; &nbsp; public int Quantity;&nbsp; &nbsp; public float GetLineItemTotal()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return Price * Quantity;&nbsp; &nbsp; }}public class CartContents{&nbsp; &nbsp; public CartEntry[] items;&nbsp; &nbsp; public float GetCartItemsTotal()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; float cartTotal = 0;&nbsp; &nbsp; &nbsp; &nbsp; foreach (CartEntry item in items)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cartTotal += item.GetLineItemTotal();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return cartTotal;&nbsp; &nbsp; }}public class Order{&nbsp; &nbsp; private CartContents cart;&nbsp; &nbsp; private float salesTax;&nbsp; &nbsp; public Order(CartContents cart, float salesTax)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this.cart = cart;&nbsp; &nbsp; &nbsp; &nbsp; this.salesTax = salesTax;&nbsp; &nbsp; }&nbsp; &nbsp; public float OrderTotal()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return cart.GetCartItemsTotal() * (1.0f + salesTax);&nbsp; &nbsp; }}特定于购物车订单项,购物车集合或订单的实现的逻辑仅限于该类。因此,我们可以更改任何这些类的实现,而不必更改其他类。我们可以通过改进设计,引入接口等来进一步消除这种耦合,但我认为您已经明白了。

PIPIONE

iPod,iPad等许多集成产品(尤其是Apple的产品)就是紧密耦合的一个很好的例子:一旦电池耗尽,您最好购买新设备,因为电池已焊接固定并且不会松动,因此更换非常容易昂贵。松散耦合的播放器可以轻松更换电池。这同样也适用于软件开发:它通常是(多)最好有松耦合代码,方便扩展和替换(并且使各个部件更容易理解)。但是,在极少数情况下,紧密耦合可能是有利的,因为几个模块的紧密集成可以实现更好的优化。
打开App,查看更多内容
随时随地看视频慕课网APP