策略模式是啥?
说白了就是同一个事情,但处理事情的方式不相同。
Order order = 订单信息
if (payType == 微信支付) {
微信支付流程
} else if (payType == 支付宝) {
支付宝支付流程
} else if (payType == 银行卡) {
银行卡支付流程
} else {
暂不支持的支付方式
}
很简单的例子,也好理解。用户要付钱,到后台就一个接口,至于你是微信还是支付宝等等,都是做一个事情快乐的收钱。
最终效果
如何实现
目录结构
上才艺(小白见解)
Controller层可以不看。主要是service层代码。
(方式一)是使用了工厂模式获取对应的实现类,有Spring工厂已经写好了何乐不为。因为要拿spring的上下文,所以随便写了一个SpringContext类。
当然还有(方式二)通过注入List的方式实现不太推荐毕竟要循环判断,可以考虑使用Map的方式。
@Controller
@RequestMapping("/test")
public class PractiseController {
@Autowired
private TestService testServiceImpl;
@RequestMapping("/test1")
@ResponseBody
public String returnStr(@RequestParam("type") String type) {
String str = testServiceImpl.outString(type);
return str;
}
}
public interface TestService {
/**
* 策略模式执行outString
* @param type: 实现类的名字
*/
String outString(String type);
public String support();
}
@Service
public class TestServiceImpl implements TestService {
// 方式一:
@Override
public String outString(String type) {
String str = "初始化字符串";
// 使用Spring工厂,拿到对应的实现类
ContentService service = SpringContext.getApplicationContext()
.getBean(type, ContentService.class);
// 执行相应方法
str = service.outString();
return str;
}
// 方式二:
@Autowired
private List<ContentService> contentServiceImpls;
@Override
public String outString(String type) {
String str = "初始化字符串";
// 使用Spring工厂,拿到对应的实现类
for (ContentService contentServiceImpl : contentServiceImpls) {
if (type.equals(contentServiceImpl.support())) {
str = contentServiceImpl.outString();
break;
}
}
return str;
}
}
@Component("test1ContentServiceImpl")
public class Test1ContentServiceImpl implements ContentService {
@Override
public String outString() {
return "我是test 1";
}
@Override
public String support() {
return "test1ContentServiceImpl";
}
}
@Component
public final class SpringContext implements ApplicationContextAware {
private SpringContext() {
}
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContext.applicationContext = applicationContext;
}
}
能看到这说明你能成大事啊!有帮助的话就留下你的足迹吧!!!