為什麼要使用接口,Java 中使用接口來實現鬆散耦合。這是一個設計原則,其目的是減少系統許多部分之間存在的依賴關係。
介面如何實現鬆散耦合:
使用介面的鬆散耦合範例
public class CreditCardPaymentService implements PaymentService { @Override public void processPayment(double amount) { // Process payment using credit card } } public class PayPalPaymentService implements PaymentService { @Override public void processPayment(double amount) { // payment processing via PayPal } } public class OrderService { private final PaymentService paymentService; public OrderService(PaymentService paymentService) { this.paymentService = paymentService; } public void placeOrder(double amount) { paymentService.processPayment(amount); } } // Usage PaymentService paymentService = new CreditCardPaymentService(); OrderService orderService = new OrderService(paymentService); orderService.placeOrder(100.0);
如範例所示,OrderService 依賴 PaymentService 接口,而不是其實作。這使您可以在多種不同的付款方式之間切換,而無需更改 OrderService 程式碼。
以上是Java 中的鬆散耦合介面的詳細內容。更多資訊請關注PHP中文網其他相關文章!