挺不错的一个设计模式,先记下来以便以后哪里可以用到:
接口:数据处理管道的阀门(处理器):
对应实现类:
接口:数据处理管道:
对应实现类:
代码:
public class DataPipelineImpl implements DataPipeline{
private List<DataValve> valveList = Lists.newArrayList(); //存放管道的阀门
private Object firstInputData;
private Object lastOutputData;
@Override
public void init() {
valveList.clear();
firstInputData =null;
lastOutputData =null;
}
@Override
public void addValve(DataValve valve) { //添加阀门
if(valve!=null){
valveList.add(valve);
}
}
@Override
public void execute() {
if(valveList.isEmpty()){
return;
}
Object tempOutputData = null;
for(int i=0;i<valveList.size();i++){ //按顺序将阀门一次添加到管道执行
DataValve valve = valveList.get(i);
if(i==0){
tempOutputData = valve.execute(firstInputData);
}else{
tempOutputData = valve.execute(tempOutputData);
}
}
this.lastOutputData = tempOutputData;
}
@Override
public Object getOutputData() {
return this.lastOutputData;
}
@Override
public void setInputData(Object data) {
this.firstInputData =data;
}
}
然后关于各个阀门(处理器):
public class Valve1SentenceSplitterImpl implements DataValve{
@Override
public Object execute(Object input) {
if (input==null || !(input instanceof String)) {
return null;
}
List<String> result = Lists.newArrayList();
List<String> list = RegexUtil.splitTextSentence((String)input);
if(CollectionUtils.isEmpty(list)){
return result;
}
//...具体业务需要的逻辑代码处理
return result;
}
}
//....其余阀门结构类似。
最后调用管道结构代码去实现:
public class DataProcessingTest {
@Autowired
private DataPipeline dataPipeline;
@Test
public void testAll() {
String id = "********";
Document doc = mongoDao.getDocById(MongoDao.********, id);
if (doc == null) {
return;
}
String content = Jsoup.parse(doc.getString("content")).text();
dataPipeline.init(); //初始化
dataPipeline.setInputData(content); //设置第一个输入元素
dataPipeline.addValve(new Valve1SentenceSplitterImpl()); //依次添加阀门对数据进行处理(就像自来水厂对水进行各种处理一样)
dataPipeline.addValve(new Valve2DataRuleImpl());
dataPipeline.addValve(new ValveDataPersistenceImpl(mongoDao));
dataPipeline.execute();
}
}