понедельник, 13 июня 2011 г.

Lazy pattern for Android

Many time I needed to do some actions "lazy" in code. Especially writing code for Android requires us to save resources of devices. There is not in problem in other languages like C#, ruby, etc. But in Java I did not find anything that could have helped me. So that here is my implementation of this pattern :)

First of all we have to declare action which should be done "lazy":

public interface ILazyAction<T> {
    T get();
}
And then create class which will evaluate our "lazy" action:
public class Lazy<T> {
    private T obj;
    private final ILazyAction<T> lazyAction;

    public Lazy(ILazyAction<T> lazyAction) {
        this.lazyAction = lazyAction;
    }

    public T getValue() {
        if (obj == null) {
            obj = lazyAction.get();
        }
        return obj;
    }
}
So that is all :) Now you can write something like
Lazy<Drawable> flag = new Lazy<Drawable>(new ILazyAction<Drawable>() {
   public Drawable get() {
        return context.getResources().getDrawable(R.drawable.flag);
     }
});
and then everywhere you can access to flag variable

flag.getValue()
So it is simple, is not it? :)
Yes, but actually there is one issue. The issue is called concurrency. The code is not thread safe because we do not expect that more than one thread can call initialization of the object.
It is easy to solve this problem:

public class Lazy<T> {
    private T obj;
    private final ILazyAction<T> lazyAction;
    private final Object lock = new Object();

    public Lazy(ILazyAction<T> lazyAction) {
        this.lazyAction = lazyAction;
    }

    public T getValue() {
        if (obj == null) {
            synchronized (lock) {
                if (obj == null) {
                    obj = lazyAction.get();
                }
            }
        }
        return obj;
    }
}
And now it is ready to work :)

Комментариев нет:

Отправить комментарий