FactoryComponent.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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> where T : Entity<T>
  8. {
  9. private Dictionary<int, IFactory<T>> allConfig;
  10. public void Load(IEnumerable<Assembly> assemblies)
  11. {
  12. allConfig = new Dictionary<int, IFactory<T>>();
  13. foreach (Assembly assembly in assemblies)
  14. {
  15. Type[] types = assembly.GetTypes();
  16. foreach (Type type in types)
  17. {
  18. object[] attrs = type.GetCustomAttributes(typeof(FactoryAttribute), false);
  19. if (attrs.Length == 0)
  20. {
  21. continue;
  22. }
  23. FactoryAttribute attribute = (FactoryAttribute)attrs[0];
  24. if (attribute.ClassType != typeof (T))
  25. {
  26. continue;
  27. }
  28. object obj = (Activator.CreateInstance(type));
  29. IFactory<T> iFactory = obj as IFactory<T>;
  30. if (iFactory == null)
  31. {
  32. throw new Exception(
  33. string.Format("class: {0} not inherit from IFactory", type.Name));
  34. }
  35. allConfig[attribute.Type] = iFactory;
  36. }
  37. }
  38. }
  39. public T Create(int configId)
  40. {
  41. int type = (int) World.Instance.GetComponent<ConfigComponent>().Get<UnitConfig>(configId).Type;
  42. return this.allConfig[type].Create(configId);
  43. }
  44. }
  45. }