首先,定義一個接口類
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博客