BuffComponent.cs 2.8 KB

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