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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
| /**
* 子系统 - 账户验证服务
*/
public class AccountVerificationService {
public boolean verifyAccount(String accountId, String password) {
System.out.println("🔐 验证账户: " + accountId);
// 模拟验证过程
if (accountId.startsWith("user") && password.length() >= 6) {
System.out.println("✅ 账户验证成功");
return true;
} else {
System.out.println("❌ 账户验证失败");
return false;
}
}
public boolean checkAccountStatus(String accountId) {
System.out.println("📊 检查账户状态: " + accountId);
// 模拟状态检查
System.out.println("✅ 账户状态正常");
return true;
}
}
/**
* 子系统 - 余额检查服务
*/
public class BalanceService {
private static final Map<String, Double> balances = new HashMap<>();
static {
balances.put("user001", 1500.0);
balances.put("user002", 800.0);
balances.put("user003", 2000.0);
}
public boolean checkBalance(String accountId, double amount) {
System.out.println("💰 检查账户余额: " + accountId);
Double balance = balances.get(accountId);
if (balance == null) {
System.out.println("❌ 账户不存在");
return false;
}
System.out.println("当前余额: ¥" + balance + ", 支付金额: ¥" + amount);
if (balance >= amount) {
System.out.println("✅ 余额充足");
return true;
} else {
System.out.println("❌ 余额不足");
return false;
}
}
public void deductBalance(String accountId, double amount) {
Double balance = balances.get(accountId);
if (balance != null && balance >= amount) {
balances.put(accountId, balance - amount);
System.out.println("💸 扣除金额: ¥" + amount + ", 剩余余额: ¥" + (balance - amount));
}
}
}
/**
* 子系统 - 风控服务
*/
public class RiskControlService {
public boolean assessRisk(String accountId, double amount, String merchantId) {
System.out.println("🛡️ 风险评估中...");
System.out.println("账户: " + accountId + ", 金额: ¥" + amount + ", 商户: " + merchantId);
// 模拟风险评估规则
if (amount > 10000) {
System.out.println("⚠️ 大额交易,需要额外验证");
return false;
}
if (accountId.contains("suspicious")) {
System.out.println("⚠️ 账户存在风险");
return false;
}
System.out.println("✅ 风险评估通过");
return true;
}
public void recordTransaction(String accountId, double amount, String merchantId) {
System.out.println("📝 记录交易信息用于风控分析");
}
}
/**
* 子系统 - 银行接口服务
*/
public class BankGatewayService {
public String processPayment(String accountId, double amount, String bankCode) {
System.out.println("🏦 连接银行网关: " + bankCode);
System.out.println("处理支付请求: 账户" + accountId + ", 金额¥" + amount);
// 模拟银行处理
try {
Thread.sleep(500); // 模拟网络延迟
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// 生成交易流水号
String transactionId = "TXN" + System.currentTimeMillis();
System.out.println("✅ 银行处理成功,交易号: " + transactionId);
return transactionId;
}
public boolean confirmTransaction(String transactionId) {
System.out.println("🏦 确认交易: " + transactionId);
System.out.println("✅ 交易确认成功");
return true;
}
}
/**
* 子系统 - 通知服务
*/
public class NotificationService {
public void sendSMS(String phoneNumber, String message) {
System.out.println("📱 发送短信到 " + phoneNumber + ": " + message);
}
public void sendEmail(String email, String subject, String content) {
System.out.println("📧 发送邮件到 " + email);
System.out.println("主题: " + subject);
System.out.println("内容: " + content);
}
public void sendPushNotification(String userId, String message) {
System.out.println("🔔 发送推送通知给用户 " + userId + ": " + message);
}
}
/**
* 子系统 - 订单服务
*/
public class OrderService {
public String createOrder(String userId, String merchantId, double amount, String description) {
String orderId = "ORDER" + System.currentTimeMillis();
System.out.println("📦 创建订单: " + orderId);
System.out.println("用户: " + userId + ", 商户: " + merchantId);
System.out.println("金额: ¥" + amount + ", 描述: " + description);
return orderId;
}
public void updateOrderStatus(String orderId, String status) {
System.out.println("📦 更新订单状态: " + orderId + " -> " + status);
}
}
/**
* 支付请求对象
*/
public class PaymentRequest {
private String userId;
private String password;
private String merchantId;
private double amount;
private String description;
private String phoneNumber;
private String email;
public PaymentRequest(String userId, String password, String merchantId,
double amount, String description, String phoneNumber, String email) {
this.userId = userId;
this.password = password;
this.merchantId = merchantId;
this.amount = amount;
this.description = description;
this.phoneNumber = phoneNumber;
this.email = email;
}
// getter方法
public String getUserId() { return userId; }
public String getPassword() { return password; }
public String getMerchantId() { return merchantId; }
public double getAmount() { return amount; }
public String getDescription() { return description; }
public String getPhoneNumber() { return phoneNumber; }
public String getEmail() { return email; }
}
/**
* 支付结果对象
*/
public class PaymentResult {
private boolean success;
private String transactionId;
private String orderId;
private String message;
private double amount;
public PaymentResult(boolean success, String transactionId, String orderId,
String message, double amount) {
this.success = success;
this.transactionId = transactionId;
this.orderId = orderId;
this.message = message;
this.amount = amount;
}
@Override
public String toString() {
return String.format("PaymentResult{success=%s, transactionId='%s', orderId='%s', message='%s', amount=%.2f}",
success, transactionId, orderId, message, amount);
}
// getter方法
public boolean isSuccess() { return success; }
public String getTransactionId() { return transactionId; }
public String getOrderId() { return orderId; }
public String getMessage() { return message; }
public double getAmount() { return amount; }
}
/**
* 外观类 - 支付系统外观
*/
public class PaymentSystemFacade {
private AccountVerificationService accountService;
private BalanceService balanceService;
private RiskControlService riskService;
private BankGatewayService bankService;
private NotificationService notificationService;
private OrderService orderService;
public PaymentSystemFacade() {
this.accountService = new AccountVerificationService();
this.balanceService = new BalanceService();
this.riskService = new RiskControlService();
this.bankService = new BankGatewayService();
this.notificationService = new NotificationService();
this.orderService = new OrderService();
}
/**
* 处理支付请求 - 主要外观方法
*/
public PaymentResult processPayment(PaymentRequest request) {
System.out.println("💳 === 开始处理支付请求 ===");
System.out.println("用户: " + request.getUserId() + ", 金额: ¥" + request.getAmount());
try {
// 1. 账户验证
if (!accountService.verifyAccount(request.getUserId(), request.getPassword())) {
return new PaymentResult(false, null, null, "账户验证失败", 0);
}
if (!accountService.checkAccountStatus(request.getUserId())) {
return new PaymentResult(false, null, null, "账户状态异常", 0);
}
// 2. 余额检查
if (!balanceService.checkBalance(request.getUserId(), request.getAmount())) {
return new PaymentResult(false, null, null, "余额不足", 0);
}
// 3. 风险评估
if (!riskService.assessRisk(request.getUserId(), request.getAmount(), request.getMerchantId())) {
return new PaymentResult(false, null, null, "风险评估未通过", 0);
}
// 4. 创建订单
String orderId = orderService.createOrder(request.getUserId(), request.getMerchantId(),
request.getAmount(), request.getDescription());
// 5. 银行支付处理
String transactionId = bankService.processPayment(request.getUserId(),
request.getAmount(), "ICBC");
// 6. 扣除余额
balanceService.deductBalance(request.getUserId(), request.getAmount());
// 7. 确认交易
bankService.confirmTransaction(transactionId);
// 8. 更新订单状态
orderService.updateOrderStatus(orderId, "PAID");
// 9. 记录风控信息
riskService.recordTransaction(request.getUserId(), request.getAmount(), request.getMerchantId());
// 10. 发送通知
sendSuccessNotifications(request, transactionId, orderId);
System.out.println("✅ 支付处理完成");
return new PaymentResult(true, transactionId, orderId, "支付成功", request.getAmount());
} catch (Exception e) {
System.out.println("❌ 支付处理失败: " + e.getMessage());
return new PaymentResult(false, null, null, "系统错误: " + e.getMessage(), 0);
}
}
/**
* 查询支付状态
*/
public PaymentResult queryPaymentStatus(String transactionId) {
System.out.println("🔍 查询支付状态: " + transactionId);
boolean confirmed = bankService.confirmTransaction(transactionId);
if (confirmed) {
return new PaymentResult(true, transactionId, null, "交易成功", 0);
} else {
return new PaymentResult(false, transactionId, null, "交易失败或不存在", 0);
}
}
/**
* 退款处理
*/
public PaymentResult processRefund(String transactionId, double refundAmount, String reason) {
System.out.println("💰 === 处理退款请求 ===");
System.out.println("交易号: " + transactionId + ", 退款金额: ¥" + refundAmount);
// 简化的退款流程
try {
// 1. 验证原交易
if (!bankService.confirmTransaction(transactionId)) {
return new PaymentResult(false, null, null, "原交易不存在", 0);
}
// 2. 处理退款
String refundId = "REFUND" + System.currentTimeMillis();
System.out.println("🏦 处理退款,退款单号: " + refundId);
// 3. 发送退款通知
System.out.println("📧 发送退款通知");
return new PaymentResult(true, refundId, null, "退款成功", refundAmount);
} catch (Exception e) {
return new PaymentResult(false, null, null, "退款失败: " + e.getMessage(), 0);
}
}
/**
* 发送成功通知
*/
private void sendSuccessNotifications(PaymentRequest request, String transactionId, String orderId) {
// 短信通知
String smsMessage = "您的支付已成功,金额¥" + request.getAmount() + ",交易号" + transactionId;
notificationService.sendSMS(request.getPhoneNumber(), smsMessage);
// 邮件通知
String emailSubject = "支付成功通知";
String emailContent = "您在商户" + request.getMerchantId() + "的支付已成功完成。\n" +
"订单号: " + orderId + "\n" +
"交易号: " + transactionId + "\n" +
"支付金额: ¥" + request.getAmount();
notificationService.sendEmail(request.getEmail(), emailSubject, emailContent);
// 推送通知
String pushMessage = "支付成功¥" + request.getAmount();
notificationService.sendPushNotification(request.getUserId(), pushMessage);
}
}
// 在线支付外观模式演示
public class PaymentSystemFacadeDemo {
public static void main(String[] args) {
System.out.println("=== 在线支付系统外观模式演示 ===");
PaymentSystemFacade paymentSystem = new PaymentSystemFacade();
System.out.println("\n=== 场景1: 成功支付 ===");
PaymentRequest request1 = new PaymentRequest(
"user001", "password123", "merchant_abc", 299.99,
"购买笔记本电脑", "138****1234", "user001@example.com"
);
PaymentResult result1 = paymentSystem.processPayment(request1);
System.out.println("\n支付结果: " + result1);
if (result1.isSuccess()) {
System.out.println("\n--- 查询支付状态 ---");
PaymentResult queryResult = paymentSystem.queryPaymentStatus(result1.getTransactionId());
System.out.println("查询结果: " + queryResult);
}
System.out.println("\n=== 场景2: 余额不足 ===");
PaymentRequest request2 = new PaymentRequest(
"user002", "password456", "merchant_xyz", 999.99,
"购买相机", "139****5678", "user002@example.com"
);
PaymentResult result2 = paymentSystem.processPayment(request2);
System.out.println("\n支付结果: " + result2);
System.out.println("\n=== 场景3: 大额交易风控拦截 ===");
PaymentRequest request3 = new PaymentRequest(
"user003", "password789", "merchant_big", 15000.0,
"购买奢侈品", "136****9012", "user003@example.com"
);
PaymentResult result3 = paymentSystem.processPayment(request3);
System.out.println("\n支付结果: " + result3);
System.out.println("\n=== 场景4: 账户验证失败 ===");
PaymentRequest request4 = new PaymentRequest(
"invalid_user", "wrong_password", "merchant_test", 50.0,
"测试商品", "137****3456", "invalid@example.com"
);
PaymentResult result4 = paymentSystem.processPayment(request4);
System.out.println("\n支付结果: " + result4);
System.out.println("\n=== 场景5: 退款处理 ===");
if (result1.isSuccess()) {
PaymentResult refundResult = paymentSystem.processRefund(
result1.getTransactionId(), 100.0, "用户申请部分退款"
);
System.out.println("退款结果: " + refundResult);
}
System.out.println("\n=== 外观模式的价值体现 ===");
System.out.println("🎯 简化了复杂的支付流程");
System.out.println("🎯 客户端只需调用一个方法即可完成支付");
System.out.println("🎯 隐藏了6个子系统的复杂交互");
System.out.println("🎯 提供了统一的错误处理和异常管理");
System.out.println("🎯 易于维护和扩展");
System.out.println("\n如果没有外观模式,客户端需要:");
System.out.println("❌ 了解并直接调用6个不同的子系统");
System.out.println("❌ 处理复杂的调用顺序和依赖关系");
System.out.println("❌ 自己处理各种异常和错误情况");
System.out.println("❌ 代码重复且容易出错");
}
}
|