FactoryComponent.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using Common.Base;
  5. namespace Model
  6. {
  7. public class FactoryComponent<T> : Component<World>, IAssemblyLoader where T : Entity<T>
  8. {
  9. private Dictionary<int, IFactory<T>> allConfig;
  10. public void Load(Assembly assembly)
  11. {
  12. allConfig = new Dictionary<int, IFactory<T>>();
  13. Type[] types = assembly.GetTypes();
  14. foreach (Type type in types)
  15. {
  16. object[] attrs = type.GetCustomAttributes(typeof(FactoryAttribute), false);
  17. if (attrs.Length == 0)
  18. {
  19. continue;
  20. }
  21. FactoryAttribute attribute = (FactoryAttribute)attrs[0];
  22. if (attribute.ClassType != typeof (T))
  23. {
  24. continue;
  25. }
  26. object obj = (Activator.CreateInstance(type));
  27. IFactory<T> iFactory = obj as IFactory<T>;
  28. if (iFactory == null)
  29. {
  30. throw new Exception(
  31. string.Format("class: {0} not inherit from IFactory", type.Name));
  32. }
  33. allConfig[attribute.Type] = iFactory;
  34. }
  35. }
  36. public T Create(int configId)
  37. {
  38. int type = World.Instance.GetComponent<ConfigComponent>().Get<UnitConfig>(configId).Type;
  39. return this.allConfig[type].Create(configId);
  40. }
  41. }
  42. }