Lahiru Kariyakaranage
Posted on July 24, 2024
Why Interfaces, Interfaces are used in Java to achieve loose coupling. which is a design principle whose aim is to reduce the dependencies that exist between many parts of the system.
how interfaces enable loose coupling:
- Abstraction: An interface provides a way to define any kind of behavior without defining how it will be implemented. This enables components to communicate with interface without having to know the details of the implementation.
- Flexibility: With interfaces, one implementation is replaced by another without any change in the dependent code. This makes a system easier for maintenance.
- Modularity: Because interfaces can provide for different components developed and tested independently, they foster modularity. Each component can be developed to conform to the interface, making sure that it can integrate with other components seamlessly.
- Dependency Injection: In Spring and similar frameworks, this is used in association with Dependency Injection, which injects the dependencies at runtime. Components are thereby more decoupled, and flexibility of a system is higher when change is required.
- Testing: Interfaces let you create unit tests that allow one to mock or stub out the dependencies easily. You can then test each element independently.
Example of Loose Coupling Using Interfaces
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);
as shown by the example, OrderService depends on the interface PaymentService, not on its implementation. This allows you to switch between multiple different ways of implementing payments without having to change the OrderService code.
💖 💪 🙅 🚩
Lahiru Kariyakaranage
Posted on July 24, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript (D): Aplicando o "Princípio da Inversão de Dependências" com Typescript e Java
November 25, 2024
java (I): Aplicando o "Princípio da Segregação da Interface" com Typescript e Java
November 25, 2024
javascript JavaScript OOP Explained: From Prototypes to Classes and the 4 Pillars of Object-Oriented Programming 🚀
October 28, 2024