UnitComponent.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Common.Base;
  5. using MongoDB.Bson;
  6. namespace Model
  7. {
  8. public class UnitComponent: Component
  9. {
  10. private readonly Dictionary<ObjectId, Unit> units =
  11. new Dictionary<ObjectId, Unit>();
  12. private readonly Dictionary<UnitType, Dictionary<ObjectId, Unit>> typeUnits =
  13. new Dictionary<UnitType, Dictionary<ObjectId, Unit>>();
  14. public void Add(Unit unit)
  15. {
  16. this.units.Add(unit.Id, unit);
  17. if (!this.typeUnits.ContainsKey(unit.Config.Type))
  18. {
  19. this.typeUnits.Add(unit.Config.Type, new Dictionary<ObjectId, Unit>());
  20. }
  21. this.typeUnits[unit.Config.Type].Add(unit.Id, unit);
  22. }
  23. public Unit Get(ObjectId id)
  24. {
  25. Unit unit = null;
  26. this.units.TryGetValue(id, out unit);
  27. return unit;
  28. }
  29. public Unit[] GetOneType(UnitType type)
  30. {
  31. Dictionary<ObjectId, Unit> oneTypeUnits = null;
  32. if (!this.typeUnits.TryGetValue(type, out oneTypeUnits))
  33. {
  34. return new Unit[0];
  35. }
  36. return oneTypeUnits.Values.ToArray();
  37. }
  38. public bool Remove(Unit unit)
  39. {
  40. if (unit == null)
  41. {
  42. throw new ArgumentNullException("unit");
  43. }
  44. if (!this.units.Remove(unit.Id))
  45. {
  46. return false;
  47. }
  48. if (!this.typeUnits[unit.Config.Type].Remove(unit.Id))
  49. {
  50. return false;
  51. }
  52. return true;
  53. }
  54. public bool Remove(ObjectId id)
  55. {
  56. Unit unit = this.Get(id);
  57. if (unit == null)
  58. {
  59. return false;
  60. }
  61. return this.Remove(unit);
  62. }
  63. }
  64. }