如何使方法首先在Java Fluent界面中弹出? [英] How to make a method pop first in java fluent interface?

查看:72
本文介绍了如何使方法首先在Java Fluent界面中弹出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个问题,对不起,如果我搞砸了. 我有一个使用Java流畅接口来实现Mail的任务. 我必须具有以下字段:发件人",收件人",主题".

This is my first asking, so sorry if I messed something. I have a task to implement a Mail, using Java fluent interface. I must have fields: From, To, Subject.

问题是,我无法使发件人"显示为第一个也是唯一一个. 例子: MailBuilder builder = new MailBuilder(); builder.from("Stiliyan").to("Alexander").subject("Welcome aboard");

The problem is, I can not make "From" to appear as first and only. Example: MailBuilder builder = new MailBuilder(); builder.from("Stiliyan").to("Alexander").subject("Welcome aboard");

但是当我输入第一个点."时.他们都出现了. (例如builder.to("a").from("b")..)

But when I type the first dot "." all of them appears. (eg builder.to("a").from("b")..)

简而言之:builder.(这里只能出现在"from"中).to("Noworries")..."

So in short: builder.(HERE MUST APPEAR ONLY "from").to("No worries")..."

这是MailBuilder.java

因此在"之后.只能出现在方法中

推荐答案

然后,每个构建器方法的声明的返回类型不能相同.但是,您仍然可以返回相同的构建器实例.例如:

Then your declared return type of each of the builder methods cannot be the same. You can still return the same builder instance though. For example:

interface IFromBuilder {
    IToBuilder from(String from);
}

interface IToBuilder {
    IMailBuilder to(String to);
}

interface IMailBuilder {
    Mail build();
}

class MailBuilder implements IFromBuilder, IToBuilder, IMailBuilder {

    private String from;
    private String to;

    @Override
    public IToBuilder from(String from) {
        this.from = from;
        return this;
    }

    @Override
    public IMailBuilder to(String to) {
        this.to = to;
        return this;
    }

    @Override
    public Mail build() {
        return new Mail(from, to);
    }
}

class Mail {
    private final String from;
    private final String to;

    public Mail(String from, String to) {
        this.from = from;
        this.to = to;
    }

    public static IFromBuilder newBuilder() {
        return new MailBuilder();
    }
}


public class Demo {
    public static void main(String[] args) {
        Mail mail = Mail.newBuilder().from("sender@a.com").to("receiver@b.com").build();
    }
}

这篇关于如何使方法首先在Java Fluent界面中弹出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆