code

package com.carl.loanpattern;

import java.util.function.Consumer;

public class FluentMailer {

    private FluentMailer() {};

    public FluentMailer from(final String address) {
        System.out.println(address);
        return this;
    }

    public FluentMailer to(final String address) {
        System.out.println(address);
        return this;
    }

    public FluentMailer subject(final String subject) {
        System.out.println(subject);
        return this;
    }

    public FluentMailer body(final String msg) {
        System.out.println(msg);
        return this;
    }

    public static void send(final Consumer<FluentMailer> block) {
        final FluentMailer mailer = new FluentMailer();
        block.accept(mailer);
        System.out.println("Sending ...");
    }

    public static void main(String[] args) {
        FluentMailer.send(mailer -> 
            mailer.from("from@test.com")
                  .to("to@test.com")
                  .subject("subject line")
                  .body("BRs")
            );
    }
}

output

from@test.com
to@test.com
subject line
BRs
Sending ...


↙↙↙阅读原文可查看相关链接,并与作者交流