Prototype Design Pattern : Mindmap and Implementation
I was going through the Gang of Four again after a long time as part of my college elective and had a very interested experience.
There are some which I misunderstood or realised had few other interesting implementations or forgot they even existed.
Now, comparing and contrasting design patterns is a funny task when all my struggle goes into remembering them.
I have been using mindmaps lately to help organize my thoughts and thought I’ll convert few design patterns into maps. Hope you would find it useful too.
Click to see the full web optimized image. Mail me/Drop a comment for a bigger one or the iMindmap file.
MindMap
Implementation
This implementation snippet is from my college CA task. The idea is to read a property file and create new instances of Coin objects. The CashPropertyLoader uses the StoreObjectFactory to clone and initialize the Coin object. Both these methods are available in the Coin object. The StoreObjectFactory also uses a StoreObjectRegistry to cache the prototypes. The StoreObjectRegistry acts as the prototype manager
publicclassStoreObjectRegistry{privatestaticMap<StoreObjectEnum,StoreObject>storeObjectRegistry=newHashMap<StoreObjectEnum,StoreObject>();publicstaticStoreObjectlookup(StoreObjectEnumstoreObjecType){StoreObjectstoreObject=null;try{StoreObjectstoreObjectImpl=null;switch(storeObjecType){caseCOIN:storeObjectImpl=newCoin();break;caseDRINK:storeObjectImpl=newDrinksBrand();break;}if(storeObjectImpl!=null){storeObjectRegistry.put(storeObjecType,storeObjectImpl);}else{System.err.println("Store Object Implementation could not be resolved. Please check your store object type and store object mapping");}storeObject=(StoreObject)storeObjectRegistry.get(storeObjecType).clone();}catch(CloneNotSupportedExceptione){e.printStackTrace();}returnstoreObject;}}
publicvoidinitialize(Map<String,String>params){ArrayList<Field>fieldsList=newArrayList<Field>();addDeclaredAndInheritedFields(this.getClass(),fieldsList);for(Fieldfield:fieldsList){field.setAccessible(true);if(params.get(field.getName())==null){continue;}try{if(field.getType()==boolean.class){field.setBoolean(this,newBoolean(params.get(field.getName())));}elseif(field.getType()==int.class){field.setInt(this,Integer.parseInt(params.get(field.getName())));}elseif(field.getType()==double.class){field.setDouble(this,Double.parseDouble(params.get(field.getName())));}else{field.set(this,params.get(field.getName()));}}catch(Exceptione){e.printStackTrace();System.out.println("Unable to map field : "+field.getName());e.printStackTrace();}}}privatestaticvoidaddDeclaredAndInheritedFields(Classc,List<Field>fields){fields.addAll(Arrays.asList(c.getDeclaredFields()));ClasssuperClass=c.getSuperclass();if(superClass!=null){addDeclaredAndInheritedFields(superClass,fields);}}publicObjectclone()throwsCloneNotSupportedException{returnsuper.clone();}