BehaviorTreeFactory.cs 2.4 KB

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