您的位置:首页 > 编程语言 > Java开发

模版模式构建可复用性大集合切片循环,使用java8 lambda去调用可以更加简洁哦

2015-05-05 17:12 597 查看
面向过程的编程思路相信大家都不陌生,随着脚本语言的盛行,面向过程的编程开始火起来了,面向过程并不是说我的代码就不面向对象了,可以把通用性的地方面向对象的思路封装,局部可复用性少的代码面向过程去编写组装。

相信用过google gauva的程序员对Lists.transfer并不陌生,这样的面向过程的语法在java8后可以非常的美丽。

其实咱们在工作中有很多过程是可抽象剥离,往往因为局部业务不同造成相当多的代码重复,这时候应该采用面向过程编程去解决这个问题。

下面这块代码在开发过程中如果不采用一定的设计模式 repeat code R会出现在我们的系统各个角落,于是乎采用模版模式来剥离变化的地方。
package com.qunar.piao.sight.common.util;

import com.google.common.annotations.GwtCompatible;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;

import java.util.Collection;
import java.util.List;

/**
* Created by yubin.qi on 2015/4/15.
*/
public class SubListUtil {

//Function<? super F, ? extends T>
public static interface SubListFuntion<T> {

public  void processor(List<T> tList);

}

public static <T> void dealForSubList(List<T> totalList, Integer subSize, SubListFuntion<T> subFuntion) {

//repeat code R--START
int count = totalList.size();
int iteratorCount = count / subSize;
for (int i = 0; i <= iteratorCount; i++) {
int endIndex, startIndex;
startIndex = i * subSize;
endIndex = ((endIndex = (i + 1) * subSize) > count) ? count : endIndex;
if (endIndex == startIndex) {
break;
}

List<T> subList = totalList.subList(startIndex, endIndex);
//---A bussiness code start
subFuntion.processor(subList);
//---A bussiness code end
}
//repeat code R--END
}

public static void main(String args[]) {
List<String> as = null;
SubListUtil.dealForSubList(as, 1000, new SubListFuntion<String>() {
@Override
public void processor(List<String> strings) {
//you want write code! or you defined method!
}
});

//java8
SubListUtil.dealForSubList(as, 1000, (strings)->{
//you want write code! or you defined method!
}));
}

}


本文出自 “程序猿De香蕉” 博客,请务必保留此出处http://qiyubin.blog.51cto.com/3642349/1642185
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐