java8 Lambda表达式+责任链模式

java8 Lambda表达式+责任链模式_第1张图片

 

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

    public void setSuccessor(ProcessingObject 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 {
    @Override
    public String handleWork(String text){
        return "From Raoul, Mario and Alan: " + text;
    }
}
class SpellCheckerProcessing extends ProcessingObject {
    @Override
    public String handleWork(String text){
        return text.replaceAll("labda", "lambda");
    }
}
class LengthProcessing extends ProcessingObject {
    @Override
    public String handleWork(String text){
        return text + "->length:" + text.length();
    }
}
public class ProcessingObjectTest {

    @Test
    public void handle() {
        ///java8以前写法
        ProcessingObject p1 = new HeaderTextProcessing();
        ProcessingObject p2 = new SpellCheckerProcessing();
        ProcessingObject 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 headerProcessing =
                (String text) -> "From Raoul, Mario and Alan: " + text;
        UnaryOperator spellCheckerProcessing =
                (String text) -> text.replaceAll("labda", "lambda");
        UnaryOperator lengthProcesing =
                (String text) -> text + " ->length:" + text.length();
        ///函数复合
        Function pipeline =
                headerProcessing.andThen(spellCheckerProcessing).andThen(lengthProcesing);
        String res = pipeline.apply("Aren't labdas really sexy?!!");
        System.out.println(res);
    }
}

 

你可能感兴趣的:(Java,设计模式,java8,lambda)