Java8 Lambda

Java8 Lambda表达式+责任链模式

2019-11-13  本文已影响0人  依然慢节奏
image image.gif

/**
 *责任链模式是一种创建处理对象序列(比如操作序列)的通用方案。一个处理对象可能需要
 * 在完成一些工作之后,将结果传递给另一个对象,这个对象接着做一些工作,再转交给下一个处
 * 理对象,以此类推。
 * 通常,这种模式是通过定义一个代表处理对象的抽象类来实现的,在抽象类中会定义一个字
 * 段来记录后续对象。一旦对象完成它的工作,处理对象就会将它的工作转交给它的后继。代码中,
 * 这段逻辑看起来是下面这样
 */
public abstract class ProcessingObject<T> {
    protected ProcessingObject<T> successor;

    public void setSuccessor(ProcessingObject<T> successor) {
        this.successor = successor;
    }
    public T handle(T input){
        T r = handleWork(input);
        if(successor != null){
            return successor.handle(r);
        }
        return r;
    }

    protected  abstract T handleWork(T input);
}
class HeaderTextProcessing extends ProcessingObject<String> {
    @Override
    public String handleWork(String text){
        return "From Raoul, Mario and Alan: " + text;
    }
}
class SpellCheckerProcessing extends ProcessingObject<String> {
    @Override
    public String handleWork(String text){
        return text.replaceAll("labda", "lambda");
    }
}
class LengthProcessing extends ProcessingObject<String> {
    @Override
    public String handleWork(String text){
        return text + "->length:" + text.length();
    }
}
image.gif
public class ProcessingObjectTest {

    @Test
    public void handle() {
        ///java8以前写法
        ProcessingObject<String> p1 = new HeaderTextProcessing();
        ProcessingObject<String> p2 = new SpellCheckerProcessing();
        ProcessingObject<String> p3 = new LengthProcessing();
        ///p1连接p2
        p1.setSuccessor(p2);
        ///p2连接p3
        p2.setSuccessor(p3);
        ///形成:p1->p2->p3的责任器链
        String result = p1.handle("Aren't labdas really sexy?!!");
        System.out.println(result);
        ///java8 lambda表达式
        UnaryOperator<String> headerProcessing =
                (String text) -> "From Raoul, Mario and Alan: " + text;
        UnaryOperator<String> spellCheckerProcessing =
                (String text) -> text.replaceAll("labda", "lambda");
        UnaryOperator<String> lengthProcesing =
                (String text) -> text + " ->length:" + text.length();
        ///函数复合
        Function<String, String> pipeline =
                headerProcessing.andThen(spellCheckerProcessing).andThen(lengthProcesing);
        String res = pipeline.apply("Aren't labdas really sexy?!!");
        System.out.println(res);
    }
}
image.gif
上一篇下一篇

猜你喜欢

热点阅读