最佳实施方式是什么:
class Ball extends View {
private Animation fallAnimation;
public void fall() {
fallAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.fall);
startAnimation(fallAnimation);
}
}
class Ball extends View {
private Animation fallAnimation;
public void fall() {
fallAnimation = BallLoader.loadFall();
startAnimation(fallAnimation);
}
}
class BallLoader {
private static Animation fallAnimation;
public static Animation loadFall() {
if (fallAnimation == null) {
fallAnimation = AnimationUtils.loadAnimation(getContext(),
R.anim.fall);
}
return fallAnimation;
}
}
class BallLoader {
private static Animation fallAnimation;
private static Animation moveAnimation;
private static Animation jumpAnimation;
public static Animation loadFall() {
if (fallAnimation == null) {
fallAnimation = AnimationUtils.loadAnimation(getContext(),
R.anim.fall);
}
return fallAnimation;
}
//not optimized, just for example
public static Animation loadMove() {
if (moveAnimation == null) {
moveAnimation = AnimationUtils.loadAnimation(getContext(),
R.anim.move);
}
return moveAnimation;
}
//not optimized, just for example
public static Animation loadJump() {
if (jumpAnimation == null) {
jumpAnimation = AnimationUtils.loadAnimation(getContext(),
R.anim.jump);
}
return jumpAnimation;
}
}
Ball ball1 = new Ball();
Ball ball2 = new Ball();
Ball ball3 = new Ball();
Ball ball4 = new Ball();
Ball ball5 = new Ball();
Ball ball6 = new Ball();
Ball ball7 = new Ball();
Ball ball8 = new Ball();
Ball ball9 = new Ball();
ball1.fall();
ball2.fall();
ball3.fall();
ball4.fall();
ball5.fall();
ball6.fall();
ball7.fall();
ball8.fall();
ball9.fall();
我认为首先是更清楚,而不是那么困惑。但是性能会有问题吗? Android每次都加载这个动画,或者它可能是由android框架缓存的?...
第二个是更混乱,原始类非常大,也许另一个程序员会混淆...我不知道,请说我什么实现更好?答案 0 :(得分:2)
这两个实现做了不同的事情。在第一个中,每个Ball对象使用不同的Animation对象。在第二个(Singleton pattern)中,所有Ball对象共享相同的Animation对象。哪个更好取决于您的要求。