java程式設計思想-程式碼賞析(一)
阿新 • • 發佈:2018-11-28
package com.test.pet; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public abstract class PetCreator { private static Random random = new Random(47); public abstract List<Class<? extends Pet>> types(); public Pet[] createArray(int size) { Pet[] pets = new Pet[size]; for (int i = 0; i < pets.length; i++) { try { pets[i] = randomPet().newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return pets; } private Class<? extends Pet> randomPet() { int n = random.nextInt(types().size()); return types().get(n); } public ArrayList<Pet> arrayList(int size) { ArrayList<Pet> result = new ArrayList<>(); Collections.addAll(result, createArray(size)); return result; } }
package com.test.pet; import java.util.ArrayList; import java.util.List; public class ForNameCreator extends PetCreator { private static List<Class<? extends Pet>> list = new ArrayList<>(); private static String[] typeNames = { "com.test.pet.Mutt", "com.test.pet.Pug", "com.test.pet.EgyptianMau", "com.test.pet.Manx", "com.test.pet.Cymric", "com.test.pet.Rat", "com.test.pet.Mouse", "com.test.pet.Hamster" }; public static void load() { for (int i = 0; i < typeNames.length; i++) { try { Class<? extends Pet> cls = (Class<? extends Pet>) Class.forName(typeNames[i]); list.add(cls); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } static { load(); } @Override public List<Class<? extends Pet>> types() { return list; } }
package com.test.pet; import java.util.HashMap; import java.util.List; public class PetCounter extends HashMap<String, Integer> { private void count(String type) { Integer count = get(type); if (count == null) put(type, 1); else put(type, ++count); } private static void counter(PetCreator petCreator) { PetCounter petCounter = new PetCounter(); for (Pet pet : petCreator.createArray(10)){ System.out.print(pet.getClass().getSimpleName() + " "); if (pet instanceof Pet) petCounter.count("Pet"); if (pet instanceof Dog) petCounter.count("Dog"); if (pet instanceof Mutt) petCounter.count("Mutt"); if (pet instanceof Pug) petCounter.count("Pug"); if (pet instanceof Cat) petCounter.count("Cat"); if (pet instanceof Manx) petCounter.count("Manx"); if (pet instanceof Cymric) petCounter.count("Cymric"); if (pet instanceof Rodent) petCounter.count("Rodent"); if (pet instanceof Rat) petCounter.count("Rat"); if (pet instanceof Mouse) petCounter.count("Mouse"); if (pet instanceof Hamster) petCounter.count("Hamster"); } System.out.println(); System.out.println(petCounter); } public static void main(String[] args) { counter(new ForNameCreator()); } }