【问题标题】:How to create class and chaining methods如何创建类和链接方法
【发布时间】:2023-03-13 01:22:01
【问题描述】:

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

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);
    }
}

我可以这样使用它:

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

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

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

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

PS 如果你知道我需要的名字,请随时编辑标题。

【问题讨论】:

标签: java class methods


【解决方案1】:

您在询问是否允许方法链接,为此,您的某些方法不应返回 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;
}

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

animation.rotate(1000, 10).play();

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

请注意,根据Marco13,这也称为Fluent Interface

顺便说一句,你会想学习和使用Java naming conventions。变量名应全部以小写字母开头,而类名应以大写字母开头。学习这一点并遵循这一点将使我们能够更好地理解您的代码,并使您能够更好地理解其他人的代码。所以将你的 myAnimations 类重命名为 MyAnimations。

【讨论】:

  • 也称为Fluent Interface
  • 不应该是MyAnimations而不是myAnimations吗?
  • @Tom:请阅读我回答的最后一段。编辑:啊,您没有阅读原始问题。有人更改了原始发帖人的代码,因为它从 public class myAnimations 开始。
  • @HovercraftFullOfEels OPs 类名是MyAnimations,但他只是编辑了它。没注意到。
  • @GiovanniDiGregorio 如果你不想把他们锁起来,那就不要这样做。
【解决方案2】:

称为Builder Design Pattern,用于避免处理过多的构造函数。

要实现它,首先你的方法返回类型应该是你的类名,你必须为你想要的所有方法返回this

因此,在您的情况下,rotate 方法的返回类型将为myAnimations

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;
}

现在,你可以按你的期望打电话了,

animation.rotate(1000, 10).play();

另外,我强烈建议对类名使用正确的命名约定。理想情况下应该是MyAnimations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2021-12-23
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多