BehaviorTreeFactory.cs 2.2 KB

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