- 首先定义支付行为接口 PayStrategy.java
package com.mbh.first_boot_demo.strategy;
/**
* @description:
* @author: mabh
* @create: 2020/5/22 10:51 下午
**/
public interface PayStrategy {
/**
* 调用支付
*/
String toPayHtml();
}
- 实现微信支付行为,实现PayStrategy接口
package com.mbh.first_boot_demo.strategy.impl;
import com.mbh.first_boot_demo.strategy.PayStrategy;
/**
* @description:
* @author: mabh
* @create: 2020/5/22 10:57 下午
**/
public class WeixinPayStrategy implements PayStrategy {
@Override
public String toPayHtml() {
System.out.println("执行微信支付.....");
return "微信支付";
}
}
- 实现阿里支付行为,实现PayStrategy接口
package com.mbh.first_boot_demo.strategy.impl;
import com.mbh.first_boot_demo.strategy.PayStrategy;
/**
* @description:
* @author: mabh
* @create: 2020/5/22 10:55 下午
**/
public class AliPayStrategy implements PayStrategy {
@Override
public String toPayHtml() {
System.out.println("调用阿里支付....");
return "阿里巴巴";
}
}
- 由于是使用枚举实现支付策略模式,当然要定义个枚举了
package com.mbh.first_boot_demo.strategy;
public enum PayEnumStrategy {
ALI_PAY("com.mbh.first_boot_demo.strategy.impl.AliPayStrategy"),
WECHAT_PAY("com.mbh.first_boot_demo.strategy.impl.WeixinPayStrategy");
private String className;
PayEnumStrategy(String className) {
this.className = className;
}
public String getClassName() {
return className;
}
}
- 支付策略工厂,这个类会根据传入的支付方式(也就是枚举名),利用生成支付策略的行为对象。
package com.mbh.first_boot_demo.strategy;
/**
* 支付策略工厂
*
* @description:
* @author: mabh
* @create: 2020/5/22 11:02 下午
**/
public class StrategyFactory {
public static PayStrategy getPayStrategy(String strategyType) {
PayEnumStrategy payEnumStrategy = PayEnumStrategy.valueOf(strategyType);
String className = payEnumStrategy.getClassName();
try {
return (PayStrategy) Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
6.定义个支付上下文,这个类也是我们支付行为的逻辑入口
package com.mbh.first_boot_demo.strategy;
import org.springframework.util.StringUtils;
/**
* 支付上下文
* @description:
* @author: mabh
* @create: 2020/5/22 11:06 下午
**/
public class PayContextStrategy {
public String toPayHtml(String payCode){
if (StringUtils.isEmpty(payCode)) {
return "payCode不能为空";
}
PayStrategy payStrategy = StrategyFactory.getPayStrategy(payCode);
if (payStrategy != null) {
return "没有具体的策略实现...";
}
return payStrategy.toPayHtml();
}
}