FactoryComponent.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. this.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(string.Format("class: {0} not inherit from IFactory", type.Name));
  31. }
  32. this.allConfig[attribute.Type] = iFactory;
  33. }
  34. }
  35. public T Create(int configId)
  36. {
  37. int type = World.Instance.GetComponent<ConfigComponent>().Get<UnitConfig>(configId).Type;
  38. return this.allConfig[type].Create(configId);
  39. }
  40. }
  41. }