Lazy initialization

In computer programminglazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.

This is typically accomplished by maintaining a flag indicating whether the process has taken place. Each time the desired object is summoned, the flag is tested. If it is ready, it is returned. If not, it is initialized on the spot.

See lazy evaluation for a general treatment of this idea. In heavily imperative languages this pattern carries hidden dangers, as does any programming habit that relies on shared state.

The "lazy factory"

In a software design pattern view, lazy initialization is often used together with a factory method pattern. This combines three ideas:

  • using a factory method to get instances of a class (factory method pattern)
  • storing the instances in a map, so you get the same instance the next time you ask for an instance with same parameter (Multiton pattern, similar to the singleton pattern)
  • using lazy initialization to instantiate the object the first time it is requested (lazy initialization pattern).

[edit]Examples

Java

Here is an example in Java.

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
 
public enum FRUIT_TYPE {
        NONE,
        APPLE,
        BANANA,
}
 
class Program {
 
        /**
         * @param args
         */
        public static void main(String[] args) {
                Fruit.getFruitByTypeName(FRUIT_TYPE.BANANA);
                Fruit.showAll();
                Fruit.getFruitByTypeName(FRUIT_TYPE.APPLE);
                Fruit.showAll();
                Fruit.getFruitByTypeName(FRUIT_TYPE.BANANA);
                Fruit.showAll();
        }
}
 
public class Fruit {
        private static Map<FRUIT_TYPE, Fruit> types = new HashMap<FRUIT_TYPE, Fruit>();
 
        /**
         * Using a private constructor to force the use of the factory method.
         * @param type
         */
        private Fruit(FRUIT_TYPE type) {
        }
 
        /**
         * Lazy Factory method, gets the Fruit instance associated with a certain
         * type. Instantiates new ones as needed.
         * @param type Any allowed fruit type, e.g. APPLE
         * @return The Fruit instance associated with that type.
         */
        public static Fruit getFruitByTypeName(FRUIT_TYPE type) {
                Fruit fruit;
 
                if (!types.containsKey(type)) {
                        // Lazy initialisation
                        fruit = new Fruit(type);
                        types.put(type, fruit);
                } else {
                        // OK, it's available currently
                        fruit = types.get(type);
                }
 
                return fruit;
        }
 
        /**
         * Lazy Factory method, gets the Fruit instance associated with a certain
         * type. Instantiates new ones as needed. Uses double-checked locking 
         * pattern for using in highly concurrent environments.
         * @param type Any allowed fruit type, e.g. APPLE
         * @return The Fruit instance associated with that type.
         */
        public static Fruit getFruitByTypeNameHighConcurrentVersion(FRUIT_TYPE type) {
                if (!types.containsKey(type)) {
                        synchronized (types) {
                                // Check again, after having acquired the lock to make sure
                                // the instance was not created meanwhile by another thread
                                if (!types.containsKey(type)) {
                                        // Lazy initialisation
                                        types.put(type, new Fruit(type));
                                }
                        }
                }
 
                return types.get(type);
        }
 
        /**
         * Displays all entered fruits.
         */
        public static void showAll() {
                if (types.size() > 0) {
                        System.out.println("Number of instances made = " + types.size());
 
                        for (Entry<FRUIT_TYPE, Fruit> entry : types.entrySet()) {
                                System.out.println(
                                                Constants.firstLetterToUpper(entry.getKey().toString()));
                        }
 
                        System.out.println();
                }
        }
}

Output

Number of instances made = 1
Banana

Number of instances made = 2
Banana
Apple

Number of instances made = 2
Banana
Apple
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值