strategy design pattern in Java #shorts #java #programming #designpatterns
Sure! Let's explain the Strategy pattern with a simple example:
**Strategy Pattern**:
**Purpose**: The Strategy pattern allows you to define a family of algorithms, encapsulate each one of them, and make them interchangeable. The pattern lets the algorithm vary independently from the clients that use it.
**Example**:
Suppose we have a simple shopping cart application that calculates the total amount based on the selected payment method. We can use the Strategy pattern to implement this.
```java
// Strategy Interface
interface PaymentStrategy {
void pay(int amount);
}
// Concrete Strategy
class CreditCardPayment implements PaymentStrategy {
private final String cardNumber;
private final String cvv;
private final String expiryDate;
public CreditCardPayment(String cardNumber, String cvv, String expiryDate) {
this.cardNumber = cardNumber;
this.cvv = cvv;
this.expiryDate = expiryDate;
}
@Override
public void pay(int amount) {
System.out.println(amount + " paid using Credit Card");
}
}
// Concrete Strategy
class PayPalPayment implements PaymentStrategy {
private final String email;
private final String password;
public PayPalPayment(String email, String password) {
this.email = email;
this.password = password;
}
@Override
public void pay(int amount) {
System.out.println(amount + " paid using PayPal");
}
}
// Context
class ShoppingCart {
private final PaymentStrategy paymentStrategy;
public ShoppingCart(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void pay(int amount) {
paymentStrategy.pay(amount);
}
}
// Usage
public class Main {
public static void main(String[] args) {
// Creating shopping cart
ShoppingCart cart = new ShoppingCart(new CreditCardPayment("1234567890123456", "123", "12/24"));
// Shopping
cart.pay(100);
// Changing the payment method
cart = new ShoppingCart(new PayPalPayment("test@example.com", "password"));
// Shopping
cart.pay(200);
}
}
```
In this example:
`PaymentStrategy` is the strategy interface.
`CreditCardPayment` and `PayPalPayment` are concrete strategies.
`ShoppingCart` is the context.
By using the Strategy pattern:
We can easily switch between different payment methods without affecting the shopping cart.
コメント