package com.jack; import com.jack.imp.IPlan; /** * 敌机工厂类: 用泛型时行了两层限制:1.必须是CLASS类型,2.必须是IEnemy实现类 * * @author laughing * @date 2014年11月20日 下午9:46:46 */ public abstract class AbstractEnemyFactory { public abstract <T extends IPlan> T createEnemy(Class<T> c); }
package com.jack; import com.jack.imp.IPlan; /** * * @author laughing * @date 2014年11月20日 下午9:50:22 */ public class EnemyFactory extends AbstractEnemyFactory { @Override public <T extends IPlan> T createEnemy(Class<T> c) { IPlan enemy = null; try { enemy = (IPlan) Class.forName(c.getName()).newInstance(); } catch (Exception e) { System.out.println("敌机生产失败."); } return (T) enemy; } }
package com.jack; import java.util.HashMap; import java.util.Map; import java.util.TimerTask; import com.jack.imp.IPlan; /** * * @author laughing * @email john.cha@qq.com * @date 2014年11月20日 下午10:07:29 */ public class EnemyManager { public static EnemyManager instance; public static Map<Integer, IPlan> enemyMap = new HashMap<Integer, IPlan>(); public static final int limtNum = 3; private int enemyID = 0; public EnemyFactory factory = new EnemyFactory(); public EnemyManager() { cratePlan(); } /** * @return the enemyMap */ public static Map<Integer, IPlan> getEnemyMap() { return enemyMap; } public void cratePlan() { java.util.Timer timer = new java.util.Timer(true); TimerTask task = new TimerTask() { public void run() { for (int i = 0; i < limtNum; i++) { IPlan plan = null; if (i == 0) { plan = factory.createEnemy(Enemy1.class); } else if (i == 1) { plan = factory.createEnemy(Enemy2.class); } else { plan = factory.createEnemy(Enemy3.class); } enemyMap.put(++enemyID, plan); } } }; timer.schedule(task, 1000, 2000); } public void clearEnemy(int key) { enemyMap.remove(key); } /** * @return the instance */ public static EnemyManager getInstance() { if (instance == null) { instance = new EnemyManager(); } return instance; } }
原文地址:http://blog.csdn.net/laughing2me/article/details/41357861