BuffComponent.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. using System.Collections.Generic;
  3. using Common.Base;
  4. using MongoDB.Bson;
  5. using MongoDB.Bson.Serialization.Attributes;
  6. namespace Model
  7. {
  8. public class BuffComponent: Component<Unit>
  9. {
  10. [BsonElement]
  11. private HashSet<Buff> buffs { get; set; }
  12. private Dictionary<ObjectId, Buff> buffIdDict { get; set; }
  13. private MultiMap<BuffType, Buff> buffTypeMMap { get; set; }
  14. public BuffComponent()
  15. {
  16. this.buffs = new HashSet<Buff>();
  17. this.buffIdDict = new Dictionary<ObjectId, Buff>();
  18. this.buffTypeMMap = new MultiMap<BuffType, Buff>();
  19. }
  20. public override void BeginInit()
  21. {
  22. base.BeginInit();
  23. this.buffs = new HashSet<Buff>();
  24. this.buffIdDict = new Dictionary<ObjectId, Buff>();
  25. this.buffTypeMMap = new MultiMap<BuffType, Buff>();
  26. }
  27. public override void EndInit()
  28. {
  29. base.EndInit();
  30. foreach (var buff in this.buffs)
  31. {
  32. this.buffIdDict.Add(buff.Id, buff);
  33. this.buffTypeMMap.Add(buff.Config.Type, buff);
  34. }
  35. }
  36. public void Add(Buff buff)
  37. {
  38. if (this.buffs.Contains(buff))
  39. {
  40. throw new ArgumentException(string.Format("already exist same buff, Id: {0} ConfigId: {1}", buff.Id, buff.Config.Id));
  41. }
  42. if (this.buffIdDict.ContainsKey(buff.Id))
  43. {
  44. throw new ArgumentException(string.Format("already exist same buff, Id: {0} ConfigId: {1}", buff.Id, buff.Config.Id));
  45. }
  46. this.buffs.Add(buff);
  47. this.buffIdDict.Add(buff.Id, buff);
  48. this.buffTypeMMap.Add(buff.Config.Type, buff);
  49. }
  50. public Buff GetById(ObjectId id)
  51. {
  52. if (!this.buffIdDict.ContainsKey(id))
  53. {
  54. return null;
  55. }
  56. return this.buffIdDict[id];
  57. }
  58. public Buff GetOneByType(BuffType type)
  59. {
  60. return this.buffTypeMMap.GetOne(type);
  61. }
  62. public Buff[] GetByType(BuffType type)
  63. {
  64. return this.buffTypeMMap.GetByKey(type);
  65. }
  66. private bool Remove(Buff buff)
  67. {
  68. if (buff == null)
  69. {
  70. return false;
  71. }
  72. this.buffs.Remove(buff);
  73. this.buffIdDict.Remove(buff.Id);
  74. this.buffTypeMMap.Remove(buff.Config.Type, buff);
  75. return true;
  76. }
  77. public bool RemoveById(ObjectId id)
  78. {
  79. Buff buff = this.GetById(id);
  80. return this.Remove(buff);
  81. }
  82. public void RemoveByType(BuffType type)
  83. {
  84. Buff[] allbuffs = this.GetByType(type);
  85. foreach (Buff buff in allbuffs)
  86. {
  87. this.Remove(buff);
  88. }
  89. }
  90. }
  91. }