如何在Java中进行方法链?o.m1().m2().m3().m4()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2872222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:53:47  来源:igfitidea点击:

How to do method chaining in Java? o.m1().m2().m3().m4()

javamethod-chaining

提问by Pentium10

I've seen in many Java code notation that after a method we call another, here is an example.

我在许多 Java 代码符号中看到,在我们调用另一个方法之后,这是一个示例。

Toast.makeText(text).setGravity(Gravity.TOP, 0, 0).setView(layout).show();

As you see after calling makeTexton the return we call setGravityand so far

正如你在调用makeText返回后看到的那样,我们调用setGravity到目前为止

How can I do this with my own classes? Do I have to do anything special?

我怎样才能用我自己的课程做到这一点?我需要做什么特别的事情吗?

采纳答案by Thomas L?tzer

This pattern is called "Fluent Interfaces" (see Wikipedia)

这种模式被称为“流畅的界面”(参见维基百科

Just return this;from the methods instead of returning nothing.

只是return this;从方法而不是什么都不返回。

So for example

所以例如

public void makeText(String text) {
    this.text = text;
}

would become

会成为

public Toast makeText(String text) {
    this.text = text;
    return this;
}

回答by Guillaume

Search for builder pattern or fluent interface on google to have more details about this.

在 google 上搜索 builder pattern 或 fluent interface 以获得更多详细信息。

Return 'this' at the end of your method can do the trick in most cases.

在大多数情况下,在您的方法末尾返回 'this' 可以解决问题。

回答by Gilbert Le Blanc

From your example:

从你的例子:

Toast.makeText(text).setGravity(Gravity.TOP, 0, 0).setView(layout).show();

Toast.makeText(text).setGravity(Gravity.TOP, 0, 0).setView(layout).show();

Each method in the chain has to return a class or an interface. The next method in the chain has to be a part of the returned class.

链中的每个方法都必须返回一个类或一个接口。链中的下一个方法必须是返回类的一部分。

We start with Toast. The method makeText, which is defined as a static method in the class Toast, has to return a class or an interface. Here, it returns an instance of the class Gravity.

我们从吐司开始。方法 makeText 在类 Toast 中定义为静态方法,必须返回一个类或一个接口。在这里,它返回一个 Gravity 类的实例。

The method setGravity, which is defined in the class Gravity, returns an instance of the class View,

在类 Gravity 中定义的 setGravity 方法返回类 View 的实例,

The method setView, which is defined in the class View, returns an instance of the class JPanel.

在类 View 中定义的方法 setView 返回 JPanel 类的一个实例。

This chain could be written out step by step.

这个链可以一步一步写出来。

Gravity gravity = Toast.makeText(text);
View view       = gravity.setGravity(Gravity.TOP, 0, 0);
JPanel panel    = view.setView(layout);
panel.show();

Writing the chain as a chain removes all of the intermediate instance variables from the source code.

将链编写为链会从源代码中删除所有中间实例变量。

回答by eric

or you can use Diezelthat generates all the interfaces you need based on a Regular expression of your fluent API.

或者您可以使用Diezel根据您的 fluent API 的正则表达式生成您需要的所有接口。

回答by subhashis

class PersonMethodChaining {
private String name;
private int age;

// In addition to having the side-effect of setting the attributes in question,
// the setters return "this" (the current Person object) to allow for further chained method calls.

public PersonMethodChaining setName(String name) {
    this.name = name;
    return this;
}

public PersonMethodChaining setAge(int age) {
    this.age = age;
    return this;
}

public void introduce() {
    System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}

// Usage:
public static void main(String[] args) {
    PersonMethodChaining person = new PersonMethodChaining();
    // Output: Hello, my name is Peter and I am 21 years old.
    person.setName("Peter").setAge(21).introduce();
}

}

}

Without method chaining

没有方法链

   class Person {
    private String name;
    private int age;

    // Per normal Java style, the setters return void.

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void introduce() {
        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
    }

    // Usage:
    public static void main(String[] args) {
        Person person = new Person();
        // Not using chaining; longer than the chained version above.
        // Output: Hello, my name is Peter and I am 21 years old.
        person.setName("Peter");
        person.setAge(21);
        person.introduce();
    }
}

Method chaining,also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement. Chaining is syntactic sugar which eliminates the need for intermediate variables. A method chain is also known as a train wreck due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together even though line breaks are often added between methods.

方法链,也称为命名参数惯用语,是在面向对象的编程语言中调用多个方法调用的常用语法。每个方法都返回一个对象,允许将调用链接到一个语句中。链接是一种语法糖,它消除了对中间变量的需要。方法链也被称为火车残骸,因为在同一行中一个接一个地出现的方法数量增加,因为更多的方法链接在一起,即使方法之间经常添加换行符。

A similar syntax is method cascading, where after the method call the expression evaluates to the current object, not the return value of the method. Cascading can be implemented using method chaining by having the method return the current object itself (this). Cascading is a key technique in fluent interfaces, and since chaining is widely implemented in object-oriented languages while cascading isn't, this form of "cascading-by-chaining by returning this" is often referred to simply as "chaining". Both chaining and cascading come from the Smalltalk language.

类似的语法是method cascading,在方法调用之后,表达式计算为当前对象,而不是方法的返回值。通过让方法返回当前对象本身(this),可以使用方法链来实现级联。级联是流畅接口中的一项关键技术,由于链式在面向对象的语言中被广泛实现,而级联不是,这种“通过返回 this 进行级联”的形式通常简称为“链式”。链接和级联都来自 Smalltalk 语言。

回答by Purushotham Kumar

Adding return this; would surely help in chaining for this class but fail for sub-classes.

添加返回这个;肯定会帮助链接这个类,但对于子类会失败。

If you want to have the chaining behaviour inherited to the sub-classes also then change your class signature as below:

如果您希望将链接行为也继承到子类,请更改您的类签名,如下所示:

Class SuperClass < SubClass extends SuperClass >{}

Class SuperClass < SubClass extends SuperClass >{}

This way all sub-classes will inherit method chaining.

这样所有子类都将继承方法链。

Example:

例子:

public class SuperClass<SubClass extends SuperClass> {

    public SubClass testMethod(){
        return (SubClass)this;
    }

    public static void main(String[] args) {
        SuperClass<SuperClass> superClass = new SuperClass<SuperClass>();
        superClass.testMethod().testMethod().testMethod();
        System.out.println(superClass.toString());
    }

}