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


  相信用过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!
        }));
    }

}