java:工厂模式+策略模式+单例模式优化if-else
1 前言
Spring的Bean管理中,xml里默认为单例模式管理Bean,加之工厂模式和策略模式,可达到减少if-else的效果。
2 使用
2.1 新建策略工厂类,并使用Spring IOC注入依赖
package com.xiaoxu.crawler.core;
import com.xiaoxu.crawler.enums.crawler.CrawlerEvent;
import com.xiaoxu.crawler.excp.AccessParamException;
import com.xiaoxu.crawler.utils.AssertUtils;
import com.xiaoxu.crawler.utils.LogUtils;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
/**
* @author xiaoxu
* @date 2022-11-11 21:23
* crawlerJ:com.xiaoxu.crawler.core.CrawlerFactory
*/
public class CrawlerFactory {
Logger crawlerLogger = LoggerFactory.getLogger(CrawlerFactory.class);
private Map<String,CrawlerStrategy> crawStrategies = new HashMap<>();
private void doCheck(){
if(MapUtils.isEmpty(this.crawStrategies)){
throw new AccessParamException(
MessageFormat.format(
"crawStrategies should not be null or empty:{0}",this.crawStrategies));
}
}
public void doProcess(CrawlerEvent event){
doCheck();
AssertUtils.assertTrue(null != event,"crawlerEvent should not be null");
CrawlerStrategy crawlerStrategy = crawStrategies.get(event.getCrawEventCode());
AssertUtils.assertTrue(null != crawlerStrategy,
"crawlerStrategy should not be null, please check config xml or CrawlerEvent enum.");
boolean res = crawlerStrategy.doCrawler();
if(!res){
LogUtils.error(crawlerLogger, "爬取视频出现错误!!!");
}
}
public void setCrawStrategies(Map<String, CrawlerStrategy> crawStrategies) {
this.crawStrategies = crawStrategies;
}
}
注意,Spring的bean的property赋值,默认是调用的实体类的setter方法,故而setCrawStrategies方法是必须的。
Spring的bean默认为scope=“singleton”,即单例模式管理Bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- scope="singleton" 单例 -->
<!-- scope="prototype" 多例 -->
<bean id="crawlerFactory" class="com.xiaoxu.crawler.core.CrawlerFactory"
scope="singleton">
<property name="crawStrategies">
<map>
<entry key="craw_tv_play" value-ref="tvPlayer"/>
<entry key="craw_movie" value-ref="movie"/>
</map>
</property>
</bean>
<bean id="tvPlayer" class="com.xiaoxu.crawler.service.crawler.impl.TVPlayCrawlerImpl"/>
<bean id="movie" class="com.xiaoxu.crawler.service.crawler.impl.MovieCrawlerImpl"/>
</beans>
package com.xiaoxu.crawler.enums.crawler;
public enum CrawlerEvent {
CRAW_TV_PLAY("craw_tv_play","tv_play","爬取电视剧"),
CRAW_MOVIE("craw_movie","movie","爬取电影");
private String crawEventCode;
private String code;
private String desc;
private CrawlerEvent(String crawEventCode,String code,String desc){
this.crawEventCode = crawEventCode;
this.code = code;
this.desc = desc;
}
public String getCrawEventCode() {
return crawEventCode;
}
public void setCrawEventCode(String crawEventCode) {
this.crawEventCode = crawEventCode;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
注入以上xml,使得策略工厂Bean生效:
2.2 新建不同的策略实现:
策略模式,即实现相同的策略接口,根据不同策略,实现不同:
public abstract class CrawlerStrategy extends Print implements CrawAction {
public abstract boolean doCrawler();
@Override
public void doCraw() {
System.out.println("我是汇总ts文件");
}
}
public interface CrawAction {
/* 爬取每个ts文件 */
CrawlerResponse crawTs(CrawlerReq crawlerReq);
/* 汇总单集ts视频文件:电视剧、电影等单集 */
void doCraw();
}
电影爬取策略实现:
public class MovieCrawlerImpl extends CrawlerStrategy {
private static final Logger logger = LoggerFactory.getLogger(MovieCrawlerImpl.class);
@Autowired
CrawlerJTemplate<MovieCrawlerRequest, MovieCrawlerResponse> crawlerJTemplate;
private static final Function<CrawlerReq, MovieCrawlerRequest> converter = (cRequest) -> {
MovieCrawlerRequest mRequest = new MovieCrawlerRequest();
mRequest.setPath(cRequest.getRequestPath());
return mRequest;
};
@Override
public boolean doCrawler() {
boolean success = false;
System.out.println("我是电影爬取的具体实现类");
return success;
}
}
电视剧爬取策略实现:
public class TVPlayCrawlerImpl extends CrawlerStrategy {
@Override
public boolean doCrawler() {
boolean isSuccess = false;
System.out.println("我是电视剧爬取具体实现类");
return isSuccess;
}
}
2.3 单测执行:
public class TestCrawlerFactory extends AbstractBaseTest {
@Autowired
CrawlerFactory factory;
@Test
public void test_one(){
factory.doProcess(CrawlerEvent.CRAW_TV_PLAY);
factory.doProcess(CrawlerEvent.CRAW_MOVIE);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CrawlerApplication.class)
public abstract class AbstractBaseTest {
protected Logger testLogger = LoggerFactory.getLogger(AbstractBaseTest.class);
}
执行效果如下:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/192106.html