pleerock
pleerock

Reputation: 18836

android and resources -> best implementation

What is the best implementation:

First:

class Ball extends View {
    private Animation fallAnimation;

    public void fall() {
        fallAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.fall);
        startAnimation(fallAnimation);
    }

}

Second:

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

}

Extend second loader:

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

}

Using of this:

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

Answers (1)

Ted Hopp
Ted Hopp

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

Related Questions