BuffComponent.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. foreach (var buff in this.Buffs)
  24. {
  25. this.buffIdDict.Add(buff.Id, buff);
  26. this.buffTypeMMap.Add(buff.Config.Type, buff);
  27. }
  28. }
  29. public void Add(Buff buff)
  30. {
  31. if (this.Buffs.Contains(buff))
  32. {
  33. throw new ArgumentException(string.Format("already exist same buff, Id: {0} ConfigId: {1}", buff.Id, buff.Config.Id));
  34. }
  35. if (this.buffIdDict.ContainsKey(buff.Id))
  36. {
  37. throw new ArgumentException(string.Format("already exist same buff, Id: {0} ConfigId: {1}", buff.Id, buff.Config.Id));
  38. }
  39. this.Buffs.Add(buff);
  40. this.buffIdDict.Add(buff.Id, buff);
  41. this.buffTypeMMap.Add(buff.Config.Type, buff);
  42. }
  43. public Buff GetById(ObjectId id)
  44. {
  45. if (!this.buffIdDict.ContainsKey(id))
  46. {
  47. return null;
  48. }
  49. return this.buffIdDict[id];
  50. }
  51. public Buff GetOneByType(BuffType type)
  52. {
  53. return this.buffTypeMMap.GetOne(type);
  54. }
  55. public Buff[] GetByType(BuffType type)
  56. {
  57. return this.buffTypeMMap.GetByKey(type);
  58. }
  59. private bool Remove(Buff buff)
  60. {
  61. if (buff == null)
  62. {
  63. return false;
  64. }
  65. this.Buffs.Remove(buff);
  66. this.buffIdDict.Remove(buff.Id);
  67. this.buffTypeMMap.Remove(buff.Config.Type, buff);
  68. return true;
  69. }
  70. public bool RemoveById(ObjectId id)
  71. {
  72. Buff buff = this.GetById(id);
  73. return this.Remove(buff);
  74. }
  75. public void RemoveByType(BuffType type)
  76. {
  77. Buff[] buffs = this.GetByType(type);
  78. foreach (Buff buff in buffs)
  79. {
  80. this.Remove(buff);
  81. }
  82. }
  83. }
  84. }