手打作业:
class Program
{
//怪兽管理器,提供创建怪物,移除怪物的方法,每个怪物有自己的唯一ID;
static void Main(string[] args)
{
MonsterManager.Instance.AddMonster();
MonsterManager.Instance.AddMonster();
MonsterManager.Instance.AddMonster();
MonsterManager.Instance.AddMonster();
MonsterManager.Instance.AddMonster();
MonsterManager.Instance.RemoveMonster(1);
MonsterManager.Instance.RemoveMonster(3);
}
class MonsterManager
{
private static MonsterManager instance = new MonsterManager();//单例
private Hashtable hashtableTable =new Hashtable();
private MonsterManager()
{
}
public static MonsterManager Instance
{
get
{
return instance;
}
}
private int monsterId = 0;
public void AddMonster()
{
Monster monster = new Monster(monsterId);
System.Console.WriteLine("创建了id为{0}的怪物", monsterId);
monsterId++;
hashtableTable.Add(monster.Id,monster );
}
public void RemoveMonster(int monsterId )
{
if (hashtableTable .ContainsKey (monsterId))
{
(hashtableTable[monsterId] as Monster).Deth();//拆箱:objiect——Monster类
hashtableTable.Remove(monsterId);
}
}
}
class Monster
{
public int Id;
public Monster(int Id)
{
this.Id = Id;
}
public void Deth()
{
System.Console.WriteLine("怪物{0}死亡",Id);
}
}
}