通过工厂模式和策略模式的结合,你实现了一个灵活且可扩展的资金账户消耗系统。工厂模式负责创建和管理不同的策略对象,而策略模式提供了不同的资金账户消耗逻辑。这种设计使得系统易于扩展和维护,同时也提高了代码的复用性和可读性。
/**
* FundAccountFactory,用于资金变动操作的工厂类
*/
@Service
public class FundAccountFactory implements ConsumeFundAccount {
/**
* 资金变动Map,存储不同业务类型的资金变动对象
*/
private final Map<String, FundAccount> fundChangeMap;
/**
* 构造函数,接收存有不同业务类型的资金变动对象的Map
* @param fundChangeMap 资金变动对象的Map
*/
public FundAccountFactory(Map<String, FundAccount> fundChangeMap) {
this.fundChangeMap = fundChangeMap;
}
@Override
public Integer consumeFundAccount(FundAccountConsumeRequest fundAccountConsumeRequest) {
// todo 后面根据其他业务进行扩展
ConsumeFundAccount consumeFundAccount = (ConsumeFundAccount) fundChangeMap.get(fundAccountConsumeRequest.getCostType().toString());
return consumeFundAccount.consumeFundAccount(fundAccountConsumeRequest);
}
}
public interface ConsumeFundAccount extends FundAccount {
/**
* 资金消耗接口
*
* @param fundAccountConsumeRequest 资金账户消耗请求参数
* @return 资金账户消耗响应参数
*/
Integer consumeFundAccount(FundAccountConsumeRequest fundAccountConsumeRequest);
}
public interface FundAccount {
// 资金账户相关操作方法可以在这里定义
}
/**
* @ClassName CpaConsumeFundAccount
* @Description CPA资金账户消耗策略实现类
* @Author zhengpengfei
* @Date 2024/5/07 14:32
**/
@Component("CPA")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CpaConsumeFundAccount implements ConsumeFundAccount {
@Resource
private FundAccountRepository fundAccountRepository;
/**
* CPA扣减逻辑
*
* @param fundAccountConsumeRequest 扣减请求参数
* @return 扣减结果
*/
@Override
public Integer consumeFundAccount(FundAccountConsumeRequest fundAccountConsumeRequest) {
return fundAccountRepository.consumeCpaFundAccount(fundAccountConsumeRequest);
}
}
@Component("CPC")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CpcConsumeFundAccount implements ConsumeFundAccount {
@Resource
private FundAccountRepository fundAccountRepository;
/**
* CPC扣减逻辑
*
* @param fundAccountConsumeRequest 扣减请求参数
* @return 扣减结果
*/
@Override
public Integer consumeFundAccount(FundAccountConsumeRequest fundAccountConsumeRequest) {
return fundAccountRepository.consumeCpcFundAccount(fundAccountConsumeRequest);
}
}
@Component("CPL")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CplConsumeFundAccount implements ConsumeFundAccount {
@Resource
private FundAccountRepository fundAccountRepository;
/**
* CPL扣减逻辑
*
* @param fundAccountConsumeRequest 扣减请求参数
* @return 扣减结果
*/
@Override
public Integer consumeFundAccount(FundAccountConsumeRequest fundAccountConsumeRequest) {
return fundAccountRepository.consumeCplFundAccount(fundAccountConsumeRequest);
}
}