BehaviorTreeFactory.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using Model;
  5. namespace BehaviorTree
  6. {
  7. public class BehaviorTreeFactory
  8. {
  9. private static readonly BehaviorTreeFactory instance = new BehaviorTreeFactory();
  10. public static BehaviorTreeFactory Instance
  11. {
  12. get
  13. {
  14. return instance;
  15. }
  16. }
  17. private readonly Dictionary<NodeType, Func<NodeConfig, Node>> dictionary =
  18. new Dictionary<NodeType, Func<NodeConfig, Node>>();
  19. private BehaviorTreeFactory()
  20. {
  21. Assembly assembly = typeof(BehaviorTreeFactory).Assembly;
  22. this.RegisterNodes(assembly);
  23. }
  24. public void RegisterNodes(Assembly assembly)
  25. {
  26. Type[] types = assembly.GetTypes();
  27. foreach (var type in types)
  28. {
  29. object[] attrs = type.GetCustomAttributes(typeof(NodeAttribute), false);
  30. if (attrs.Length == 0)
  31. {
  32. continue;
  33. }
  34. NodeAttribute attribute = (NodeAttribute)attrs[0];
  35. Type classType = type;
  36. this.dictionary.Add(attribute.NodeType,
  37. config =>
  38. (Node)Activator.CreateInstance(classType, new object[] { config }));
  39. }
  40. }
  41. private Node CreateNode(NodeConfig config)
  42. {
  43. if (!this.dictionary.ContainsKey((NodeType) config.Id))
  44. {
  45. throw new KeyNotFoundException(string.Format("CreateNode cannot found: {0}",
  46. config.Id));
  47. }
  48. return this.dictionary[(NodeType) config.Id](config);
  49. }
  50. private Node CreateTreeNode(NodeConfig config)
  51. {
  52. var node = this.CreateNode(config);
  53. if (config.SubConfigs == null)
  54. {
  55. return node;
  56. }
  57. foreach (var subConfig in config.SubConfigs)
  58. {
  59. var subNode = this.CreateTreeNode(subConfig);
  60. node.AddChild(subNode);
  61. }
  62. return node;
  63. }
  64. public BehaviorTree CreateTree(NodeConfig config)
  65. {
  66. var node = this.CreateTreeNode(config);
  67. return new BehaviorTree(node);
  68. }
  69. }
  70. }