packageidv.design.pattern.singleton.extend;importjava.util.HashMap;importjava.util.Map;/** * @author Carl Lu */publicclassExtendSingleton {/* * 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 * */privatestaticfinalString DEFAULT_KEY ="Cache";/* * The max number of the instance. */privatefinalstaticint MAX_INSTANCE_NUM =3;/* * This variable is for counting the current number of the instance. */privatestaticint currentInstanceNumber =1;privatestaticMap<String,ExtendSingleton> map =newHashMap<String,ExtendSingleton>();privateExtendSingleton() { }publicstaticExtendSingletongetInstance() {String key = DEFAULT_KEY + currentInstanceNumber;ExtendSingleton singleton =map.get(key);if(singleton ==null) { singleton =newExtendSingleton();map.put(key, singleton); } currentInstanceNumber++;if(currentInstanceNumber > MAX_INSTANCE_NUM) { currentInstanceNumber =1; }return singleton; }}