Reputation: 18836
What is the best implementation:
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();
I think that first is more clear and not so confused. But will be there any problems with performance? Android loads this animations every time or maybe it's caching by android framework?...
Second is more confused and original class is very large and maybe another programmers will confused with that... I don't know, please say me what implementation is better?
Upvotes: 0
Views: 348
Reputation: 234795
The two implementations do different things. In the first, each Ball object uses a distinct Animation object. In the second (which is a Singleton pattern), the same Animation object is shared by all Ball objects. Which is better depends on your requirements.
Upvotes: 2