1.5 Extend Singleton

我個人認為, singleton的精華就是要"控制實例的數量", 為了實現這個概念, 你可以在你的類別裡面去對元件實例的數量做控制, 以下直接用程式說明:

package idv.design.pattern.singleton.extend;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Carl Lu
 */
public class ExtendSingleton {

    /*
     * The essence of singleton pattern is to "Control the number of instance."
     * So, to extend this concept, imagine that you need to develop a component
     * that the number of the component instance can be controlled by you in the class.
     * To fulfill this functionality, we can combine the concept of:
     *
     *      1. Singleton pattern
     *      2. Cache mechanism
     *
     */

    private static final String DEFAULT_KEY = "Cache";

    /*
     * The max number of the instance.
     */
    private final static int MAX_INSTANCE_NUM = 3;

    /*
     * This variable is for counting the current number of the instance.
     */
    private static int currentInstanceNumber = 1;

    private static Map<String, ExtendSingleton> map = new HashMap<String, ExtendSingleton>();

    private ExtendSingleton() {

    }

    public static ExtendSingleton getInstance() {
        String key = DEFAULT_KEY + currentInstanceNumber;
        ExtendSingleton singleton = map.get(key);
        if(singleton == null) {
            singleton = new ExtendSingleton();
            map.put(key, singleton);
        }

        currentInstanceNumber++;
        if(currentInstanceNumber > MAX_INSTANCE_NUM) {
            currentInstanceNumber = 1;
        }

        return singleton;
    }

}

原始碼點我

你可能會說: "這樣實例就不止一個了呀!". 對啊, 我上面寫了是要"控制實例的數量", 所以這邊當然可以不止一個了, 其實就是針對控制數量這個概念去做的一個延伸吧, 參考看看即可.

Last updated