[英]How to create class and chaining methods
我构建了一个类 (例如一个类来制作简单的动画):
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
所以我可以调用这个双重方法 (我不知道名字), 我应该如何构建我的类?
如果您知道我需要的名称,请随时编辑标题。
你问的是允许方法链接并且这样做,你的一些方法不应该返回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();
您需要为要允许链接的每个方法执行此操作。
另外,您将需要学习和使用Java命名约定 。 变量名都应以较低的字母开头,而类名以大写字母开头。 学习这一点并遵循这一点将使我们能够更好地理解您的代码,并使您能够更好地理解其他代码。 因此,将myAnimations类重命名为MyAnimations。
它被称为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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.