-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStrategy.java
83 lines (71 loc) · 2.31 KB
/
Strategy.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Payment Strategy Interface
interface PaymentStrategy {
boolean pay(double amount);
}
// Concrete Strategy: CreditCard Payment
class CreditCardPayment implements PaymentStrategy {
@Override
public boolean pay(double amount) {
System.out.println("Making payment using Credit Card: $" + amount);
// Perform credit card payment logic
return true;
}
}
// Concrete Strategy: PayPal Payment
class PayPalPayment implements PaymentStrategy {
@Override
public boolean pay(double amount) {
System.out.println("Making payment using PayPal: $" + amount);
// Perform PayPal payment logic
return true;
}
}
// Concrete Strategy: Bank Transfer Payment
class BankPayment implements PaymentStrategy {
@Override
public boolean pay(double amount) {
System.out.println("Making payment using Bank Transfer: $" + amount);
// Perform bank transfer payment logic
return true;
}
}
// Concrete Strategy: Bkash Payment
class BkashPayment implements PaymentStrategy {
@Override
public boolean pay(double amount) {
System.out.println("Making payment using Bkash: $" + amount);
// Perform Bkash payment logic
return true;
}
}
// Context Class: PaymentSystem
class PaymentSystem {
private PaymentStrategy paymentStrategy;
// Set the payment strategy at runtime
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
// Process payment using the selected strategy
public boolean makePayment(double amount) {
if (paymentStrategy == null) {
System.out.println("Payment strategy is not set.");
return false;
}
return paymentStrategy.pay(amount);
}
}
// Main Class
public class Strategy {
public static void main(String[] args) {
PaymentSystem paymentSystem = new PaymentSystem();
// Pay using Bank Transfer
paymentSystem.setPaymentStrategy(new BankPayment());
paymentSystem.makePayment(200);
// Pay using Bkash
paymentSystem.setPaymentStrategy(new BkashPayment());
paymentSystem.makePayment(500);
// Pay using Credit Card
paymentSystem.setPaymentStrategy(new CreditCardPayment());
paymentSystem.makePayment(5500);
}
}