Java 可以更新其他对象的动画类';价值观
我想要一个动画类,可以通过不同的项目重用。问题是如何让类更改另一个对象的成员(例如位置)。下面是一个非常简单的版本,它将如何运行以及它可以做什么Java 可以更新其他对象的动画类';价值观,java,animation,Java,Animation,我想要一个动画类,可以通过不同的项目重用。问题是如何让类更改另一个对象的成员(例如位置)。下面是一个非常简单的版本,它将如何运行以及它可以做什么 public class Animation() { private float currValue, targetValue, duration; public Animation(currValue, targetValue, duration) { this.currValue = currValue;
public class Animation() {
private float currValue, targetValue, duration;
public Animation(currValue, targetValue, duration) {
this.currValue = currValue;
this.targetValue = targetValue;
this.duration = duration;
}
public void update() {
// Here I would update its currValue based on duration and target
}
}
所以,当我想设置一个矩形的位置动画时,我会:
class Rectangle {
private float x, y;
private Animation a;
public Rectangle (x, y) {
this.x = x;
this.y = y;
this.a = new Animation(x, 100, 1000); // Duration in ms
}
public void update() {
a.update(); // Update animation
}
}
显然,这不起作用,因为动画不会更新矩形的x值。只想到一种解决方案,即传入矩形实例和字段名“x”,然后使用反射API更新值。但这似乎是一个相当糟糕的解决方案
有什么建议吗?我应该以不同的方式设计代码吗?在这种情况下,反射不一定是一个糟糕的解决方案。事实上,这是一个非常通用的解决方案,允许在客户端编写优雅的代码。但是,当然,人们应该知道使用反射的警告 这种动画的一种非常实用的方法是“考虑”动画的实际功能:即在您的情况下,更改一些
float
值。因此,分离“客户机”代码和实现的一种方法可以是:
interface FloatSetter {
void setFloat(float f);
}
public class Animation
{
private float currValue, targetValue, duration;
private FloatSetter floatSetter;
public Animation(
float currValue, float targetValue, float duration,
FloatSetter floatSetter)
{
this.currValue = currValue;
this.targetValue = targetValue;
this.duration = duration;
this.floatSetter = floatSetter;
}
public void update()
{
...
floatSetter.setFloat(currValue);
}
}
然后可以将FloatSetter
的适当实现传递给动画
——可能通过匿名内部类:
class Rectangle
{
private float x, y;
private Animation a;
public Rectangle(float fx, float fy) {
this.x = fx;
this.y = fy;
FloatSetter floatSetter = new FloatSetter()
{
@Override
public void setFloat(float f)
{
this.x = f;
}
});
this.a = new Animation(x, 100, 1000, floatSetter);
}
public void update() {
a.update(); // Update animation
}
}
顺便说一句:根据您将要实现的目标,我建议不要将动画
实例放入矩形
。但我想这只是一个草图来表达你的意图
重要:您应该明确了解“时间框架”:。这是Chet Haase和Romain Guy写的《肮脏的有钱客户》一书中章节的附带代码,他们当然知道自己的东西。该库是一个非常复杂和灵活的实现,显然是您想要在那里实现的。(它们还支持使用反射()的通用“PropertySetter”,但这只是一个用于定义通用“TimingTarget”的帮助器类,它是我在上面绘制的“FloatSetter”的复杂版本) 我认为“可重用”是指Swing项目中的可重用?你可以看看下面的例子