首先,定义一个接口类
import java.util.Map;public interface PayInterface {/*** 支付方法* @param amount 支付金额* @param paymentInfo 支付信息(如卡号、密码等)* @return 支付结果*/boolean pay(double amount, Map<String, String> paymentInfo);
}
再写俩个实现类
import java.util.Map;public class Pay1 implements PayInterface {@Overridepublic boolean pay(double amount, Map<String, String> paymentInfo) {System.out.println("使用支付宝支付:" + amount + "元");// 实际支付宝支付逻辑...// 验证支付信息// 调用支付宝API// 处理支付结果return true; // 假设支付成功}
}
import java.util.Map;public class Pay2 implements PayInterface {@Overridepublic boolean pay(double amount, Map<String, String> paymentInfo) {System.out.println("使用微信支付:" + amount + "元");// 实际微信支付逻辑...// 验证支付信息// 调用微信支付API// 处理支付结果return true; // 假设支付成功}
}
此时就把支付逻辑的类写完了。
再封装一个上下文信息的类。
import java.util.Map;/*** 支付上下文*/
class PaymentContext {private PayInterface paymentStrategy;public PaymentContext(PayInterface paymentStrategy) {this.paymentStrategy = paymentStrategy;}public void setPaymentStrategy(PayInterface paymentStrategy) {this.paymentStrategy = paymentStrategy;}public boolean executePayment(double amount, Map<String, String> paymentInfo) {return paymentStrategy.pay(amount, paymentInfo);}
}
以及一个生成支付实例的工厂类
public class PayFactory {public static PayInterface getStrategy(String paymentType) {switch (paymentType.toLowerCase()) {case "alipay":return new Pay1();case "wechat":return new Pay2();default:throw new IllegalArgumentException("不支持的支付方式: " + paymentType);}}
}
此时准备工作完成了。
import java.util.HashMap;
import java.util.Map;public class Main {public static void main(String[] args) {// 准备支付信息Map<String, String> paymentInfo = new HashMap<>();paymentInfo.put("account", "user123");paymentInfo.put("password", "123456");paymentInfo.put("cardNumber", "622588******1234"); // 银行卡支付需要// 创建支付上下文PaymentContext context = new PaymentContext(PayFactory.getStrategy("wechat"));// 使用支付宝支付boolean result1 = context.executePayment(100.0, paymentInfo);System.out.println("支付宝支付结果: " + (result1 ? "成功" : "失败"));// 动态切换到微信支付context.setPaymentStrategy(PayFactory.getStrategy("alipay"));boolean result2 = context.executePayment(200.0, paymentInfo);System.out.println("微信支付结果: " + (result2 ? "成功" : "失败"));//添加银行卡支付方式,可以通过动态代理的方式进行实现,不展开介绍可以看看proxy包的实现}
}
此时就完成了 一个支付模块的设计,能够支持动态选择支付方式,而不是大量的ifelse操作,
但是以上还有很多增加的点,
比如工厂类的写法有待改进,上面只是简单写法,还有如果需要动态的创建新的支付方式呢,难道只能停止运行创建完再手动运行吗?这样太麻烦了,我们可以使用动态代理的方式在运行期进行创建支付方式,怎么创建呢?
需要有一定的动态代理基础,我们写一个接口,能够生成统一模板的支付类,并将其编译加载到JVM中,然后验证其正确性和稳定性,最后将其注册到工厂类中即可供用户使用。
深入理解Java的动态代理机制,手写一个简易的动态代理-CSDN博客