FactoryComponent.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. var 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 type, int configId)
  36. {
  37. return this.allConfig[type].Create(configId);
  38. }
  39. }
  40. }