如何创建类和链接方法

Gio*_*rio 2 java methods class

我构建了一个(例如一个类来制作简单的动画):

public class myAnimations {

    private Animation animation;
    private ImageView imageView;

    public myAnimations(ImageView img) {
        super();
        this.imageView = img;
    }

    public void rotate(int duration, int repeat) {
        animation = new RotateAnimation(0.0f, 360.0f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setRepeatCount(repeat);
        animation.setDuration(duration);
    }

    public void play() {
        imageView.startAnimation(animation);
    }

    public void stop() {
        animation.setRepeatCount(0);
    }
}
Run Code Online (Sandbox Code Playgroud)

我只是可以这样使用它:

ImageView myImage = (ImageView) findViewById(R.id.my_image);
myAnimations animation = new myAnimations(myImage);
animation.rotate(1000, 10);
animation.play(); //from this way…
Run Code Online (Sandbox Code Playgroud)

但如果我想能够像这样使用它:

ImageView myImage = (ImageView) findViewById(R.id.my_image);
myAnimations animation = new myAnimations(myImage);
animation.rotate(1000, 10).play(); //…to this way
Run Code Online (Sandbox Code Playgroud)

所以我可以调用这个双重方法(我不知道名字),我应该如何构建我的类?

如果您知道我需要的名称,请随时编辑标题.

Hov*_*els 7

你问的是允许方法链接并且这样做,你的一些方法不应该返回void,而应该返回它们this.例如:

// note that it is declared to return myAnimation type
public MyAnimations rotate(int duration, int repeat) {
    animation = new RotateAnimation(0.0f, 360.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    animation.setRepeatCount(repeat);
    animation.setDuration(duration);
    return this;
}
Run Code Online (Sandbox Code Playgroud)

因此,当调用此方法时,您可以将另一个方法调用链接到它,因为它返回当前对象:

animation.rotate(1000, 10).play();
Run Code Online (Sandbox Code Playgroud)

您需要为要允许链接的每个方法执行此操作.

请注意,根据Marco13,这也称为Fluent界面.

另外,您将需要学习和使用Java命名约定.变量名都应以较低的字母开头,而类名以大写字母开头.学习这一点并遵循这一点将使我们能够更好地理解您的代码,并使您能够更好地理解其他代码.因此,将myAnimations类重命名为MyAnimations.

  • 也称为[流畅的界面](https://en.wikipedia.org/wiki/Fluent_interface) (3认同)