java使用策略模式完成多种支付方式代码实现
策略模式是一种行为型设计模式,它定义了一系列的算法,并将每个算法封装到独立的类中,使得它们可以互相替换。在这个问题中,我们可以使用策略模式来实现多种支付方式。
首先,我们需要创建一个接口,定义支付方式的通用行为:
public interface PaymentStrategy {
void pay(double amount);
}
然后,我们可以创建不同的支付方式类,实现接口中的方法:
public class CreditCardStrategy implements PaymentStrategy {
private String cardNumber;
private String cvv;
private String expiryDate;
public CreditCardStrategy(String cardNumber, String cvv, String expiryDate) {
this.cardNumber = cardNumber;
this.cvv = cvv;
this.expiryDate = expiryDate;
}
@Override
public void pay(double amount) {
// 实现信用卡支付的逻辑
System.out.println(amount + " paid with credit card");
}
}
public class PayPalStrategy implements PaymentStrategy {
private String email;
private String password;
public PayPalStrategy(String email, String password) {
this.email = email;
this.password = password;
}
@Override
public void pay(double amount) {
// 实现PayPal支付的逻辑
System.out.println(amount + " paid with PayPal");
}
}
public class AliPayStrategy implements PaymentStrategy {
private String account;
private String password;
public AliPayStrategy(String account, String password) {
this.account = account;
this.password = password;
}
@Override
public void pay(double amount) {
// 实现支付宝支付的逻辑
System.out.println(amount + " paid with AliPay");
}
}
最后,我们可以创建一个使用支付策略的类:
public class PaymentContext {
private PaymentStrategy paymentStrategy;
public PaymentContext(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void pay(double amount) {
paymentStrategy.pay(amount);
}
}
使用示例:
public class Main {
public static void main(String[] args) {
PaymentContext paymentContext = new PaymentContext(new CreditCardStrategy("1234567890", "123", "01/23"));
paymentContext.pay(100.0);
paymentContext = new PaymentContext(new PayPalStrategy("test@example.com", "password"));
paymentContext.pay(200.0);
paymentContext = new PaymentContext(new AliPayStrategy("test@example.com", "password"));
paymentContext.pay(300.0);
}
}
输出结果:
100.0 paid with credit card
200.0 paid with PayPal
300.0 paid with AliPay
这样就完成了使用策略模式实现多种支付方式的代码实现。不同的支付方式被封装到不同的类中,通过创建不同的支付策略对象,可以在运行时选择不同的支付方式进行支付
原文地址: https://www.cveoy.top/t/topic/iW7w 著作权归作者所有。请勿转载和采集!