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":
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:
First of all we have to declare action which should be done "lazy":
And then create class which will evaluate our "lazy" action:public interface ILazyAction<T> { T get(); }
So that is all :) Now you can write something likepublic 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; } }
and then everywhere you can access to flag variableLazy<Drawable> flag = new Lazy<Drawable>(new ILazyAction<Drawable>() { public Drawable get() { return context.getResources().getDrawable(R.drawable.flag); } });
So it is simple, is not it? :)flag.getValue()
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:
And now it is ready to work :)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; } }