protected override void RealTestOutPut() { Composite root = new Composite("root", 0); Composite branch1 = new Composite("branch", 1); Composite branch2 = new Composite("branch", 1); Composite branch11 = new Composite("branch", 2); branch1.AddChild(new Leaf("tac", 1)); branch1.AddChild(new Leaf("anit", 1)); branch2.AddChild(new Leaf("tac2", 2)); branch2.AddChild(new Leaf("anit2", 2)); branch11.AddChild(new Leaf("tac11", 3)); branch11.AddChild(new Leaf("anit11", 3)); root.AddChild(branch1); root.AddChild(branch2); branch1.AddChild(branch11); root.AcceptForEach(new PrintAndComposing()); branch1.RemoveChild(branch11); root.AcceptForEach(new PrintAndComposing()); branch1.Parent.AcceptForEach(new PrintAndComposing()); branch1.GetChild(1).Parent.AcceptForEach(new PrintAndComposing()); }
public void Composite_Test() { var composite = new Composite(); composite.AddChild(new DesignPatternsLib.StructuralPatterns.Composite.Component()); var subcomposite = new Composite(); subcomposite.AddChild(new DesignPatternsLib.StructuralPatterns.Composite.Component()); subcomposite.AddChild(new Leaf()); composite.AddChild(subcomposite); composite.AddChild(new Composite()); composite.AddChild(new Leaf()); int countChild = 0; int countSubChild = 0; foreach (var item in composite) { if (item as Composite != null) { foreach (var item2 in item as Composite) { countSubChild++; } } countChild++; } Assert.AreEqual(countChild, 4); Assert.AreEqual(countSubChild, 2); }
public static void CompositeQuestion() { Component root = new Composite("Canvas root"); Component circle1 = new Leaf("Circle 1"); Component rectangle = new Leaf("Rectangle x"); root.AddChild(circle1); root.AddChild(rectangle); Component container1 = new Composite("Container 1"); Component circle2 = new Leaf("Circle 1"); Component circle3 = new Leaf("Circle 2"); container1.AddChild(circle2); container1.AddChild(circle3); root.AddChild(container1); Component container2 = new Composite("Container of triangles"); Component t1 = new Leaf("Triangle 1"); Component t2 = new Leaf("Triangle 2"); container2.AddChild(t1); container2.AddChild(t2); root.AddChild(container2); root.Draw(""); Console.WriteLine($"ROOT COUNT: {root.CountLeaf()}"); Console.WriteLine($"isBinary {isBinary(root)}"); }
static Composite CreateMenu(Bank bank) { Console.WriteLine(bank); Composite menu = new Composite("MainMenu", bank); Composite info = new Composite("Info", bank, menu); info.AddChild(new Invoker("About Us", new AboutBankCommand(bank))); info.AddChild(new Invoker("Contact Us", new ContactBankCommand(bank))); Composite profile = new Composite("Profile", bank, menu, Access.User); Composite converts = new Composite("Convert", bank, profile); converts.AddChild(new Invoker("TO_USD", new ConvertToUSDCommand(bank))); converts.AddChild(new Invoker("TO_EUR", new ConvertToEURCommand(bank))); converts.AddChild(new Invoker("TO_UAH", new ConvertToUAHCommand(bank))); converts.AddChild(new Invoker("TO_RUB", new ConvertToRUBCommand(bank))); Composite settings = new Composite("Settings", bank, profile); Composite methodTopUp = new Composite("Top up the Phone", bank, settings); methodTopUp.AddChild(new Invoker("Cash Method", new CashTopUpCommand(bank))); methodTopUp.AddChild(new Invoker("Card Method", new CardTopUpCommand(bank))); methodTopUp.AddChild(new Invoker("BitCoin Method", new BitCoinTopUpCommand(bank))); Composite upgradeNotify = new Composite("Upgrade Account Notification ", bank, settings); upgradeNotify.AddChild(new Invoker("Set EmailNotification", new EmailNotificationCommand(bank))); upgradeNotify.AddChild(new Invoker("Set FaceBookNotification", new FacebookNotificationCommand(bank))); upgradeNotify.AddChild(new Invoker("Set TelegramNotification", new TelegramNotificationCommand(bank))); settings.AddChild(methodTopUp); settings.AddChild(upgradeNotify); profile.AddChild(new Invoker("Info", new AccountInfoCommand(bank))); profile.AddChild(new Invoker("Top Up The Phone", new TopUpCommand(bank))); profile.AddChild(new Invoker("Send Notification", new SendNotificationCommand(bank))); profile.AddChild(converts); profile.AddChild(settings); profile.AddChild(new Invoker("Log Out", new LogOutCommand(bank))); menu.AddChild(info); menu.AddChild(new Invoker("Login", new LoginCommand(bank), Access.OnlyGuest)); menu.AddChild(new Invoker("Sign Up", new RegisterCommand(bank), Access.OnlyGuest)); menu.AddChild(profile); menu.AddChild(new Invoker("Log Out", new LogOutCommand(bank), Access.User)); return(menu); }
public BTEditorGraphNode OnCreateChild(BehaviourNode node) { if (node != null && ((m_node is Composite) || (m_node is Decorator))) { if (m_node is Composite) { Composite composite = m_node as Composite; composite.AddChild(node); } else if (m_node is Decorator) { Decorator decorator = m_node as Decorator; DestroyChildren(); decorator.SetChild(node); } BTEditorGraphNode graphNode = BTEditorGraphNode.CreateExistingNode(this, node); m_children.Add(graphNode); BTEditorCanvas.Current.RecalculateSize(node.Position); return(graphNode); } return(null); }
static void Main(string[] args) { Composite root = new Composite("root"); root.AddChild(new Leaf("Leaf 1-A")); Composite composite = new Composite("Composite 1-B"); composite.AddChild(new Leaf("Leaf 2-A")); composite.AddChild(new Leaf("Leaf 2-B")); root.AddChild(composite); root.AddChild(new Leaf("Leaf 1-C")); root.doOperation(); Console.Read(); }
void Start() { Composite root = new Composite("Root"); Composite node1 = new Composite("Node1"); Leaf node2 = new Leaf("Node2"); Leaf node3 = new Leaf("Node3"); root.AddChild(node1); root.AddChild(node2); root.AddChild(node3); Leaf child1 = new Leaf("Child1"); Leaf child2 = new Leaf("Child2"); node1.AddChild(child1); node1.AddChild(child2); ReadRoot(root); }
public static void Main() { var root = new Composite("root"); root.AddChild(new Leaf("Leaf 1")); root.AddChild(new Leaf("Leaf 2")); var comp = new Composite("Composite C"); comp.AddChild(new Leaf("Leaf C.1")); comp.AddChild(new Leaf("Leaf C.2")); root.AddChild(comp); root.AddChild(new Leaf("Leaf 3")); var leaf = new Leaf("Leaf 4"); root.AddChild(leaf); root.RemoveChild(leaf); root.Display(1); }
void Start() { MyCompoment _1stCom = new Composite("第一层Composite"); MyCompoment _2rdCom = new Composite("第二层Composite"); MyCompoment _2rdLeaf = new Leaf("第二层Leaf"); MyCompoment _3rdLeaf = new Leaf("第三层Leaf"); _1stCom.AddChild(_2rdCom); _1stCom.AddChild(_2rdLeaf); _2rdCom.AddChild(_3rdLeaf); _1stCom.Operation(); print("\n"); _2rdCom.Operation(); print("\n"); _2rdLeaf.Operation(); }
private static void RunGoF() { hr(); con("Lets plant a tree to honor our mad scientists."); hr(); // First we will create a new composite root object. var root = new Composite("ROOT"); // Then add some leaves. (leaves cannot have children BTW) root.AddChild(new Leaf("Leaf A")); root.AddChild(new Leaf("Leaf B")); // Next we will add a composite branch that can have children. var branch = new Composite("Branch 1"); // We add it as a child of the root. root.AddChild(branch); // Since the branch can have children let's add some leaves. branch.AddChild(new Leaf("Leaf 1A")); branch.AddChild(new Leaf("Leaf 1B")); // Let's add some colored leaves next to our branch. var brownLeaf = new Leaf("Brown Leaf"); var greenLeaf = new Leaf("Green Leaf"); branch.AddChild(brownLeaf); branch.AddChild(greenLeaf); // Since we want to keep our tree green, let's remone the brown leaf. branch.RemoveChild(brownLeaf); // Now let's write out our entire tree to JSON con(root.ToPrettyJson()); // Notice - the brown leaf is no longer there. }
public static void LoadGraph(SerializedGraph graph, BehaviourTree behaviourTree, BlackboardManager bbManager) { EntryTask graphEntry = null; Dictionary <string, Task> tasks = new Dictionary <string, Task>(); for (int i = 0; i < graph.Nodes.Count; i++) { var serializedNode = graph.Nodes[i]; Type behaviourType = serializedNode.NodeRuntimeType; if (behaviourType == typeof(EntryTask)) { graphEntry = Activator.CreateInstance <EntryTask>(); tasks.Add(serializedNode.Guid, graphEntry); } else { var task = (Task)JsonUtility.FromJson(graph.Nodes[i].NodeJSONData, behaviourType);//(Task)Activator.CreateInstance(behaviourType); tasks.Add(serializedNode.Guid, task); bbManager.BindTask(behaviourTree, task); } } for (int i = 0; i < graph.Edges.Count; i++) { var serializedEdge = graph.Edges[i]; Debug.Log($"{serializedEdge.SourceNodeGUID} ---> {serializedEdge.TargetNodeGUID}"); Task source = tasks[serializedEdge.SourceNodeGUID]; Task target = tasks[serializedEdge.TargetNodeGUID]; if (source is EntryTask) { EntryTask entry = (EntryTask)source; entry.TreeRoot = target; } else if (source is Composite) { Composite composite = (Composite)source; composite.AddChild(target); } else if (source is Decorator) { Decorator decorator = (Decorator)source; decorator.Decoratee = target; } } behaviourTree.Root = graphEntry; }
static void Main(string[] args) { Leaf leaf1 = new Leaf(); Leaf leaf2 = new Leaf(); Leaf leaf3 = new Leaf(); Composite composite = new Composite(); composite.AddChild(leaf1); composite.AddChild(leaf2); composite.AddChild(leaf3); List <IComponent> listchildren = composite.GetChild(); Console.WriteLine(listchildren.Count); leaf1.operation(); leaf2.operation(); composite.operation(); Console.ReadKey(); }
public void OnNodeSwitchType(BTEditorGraphNode target, Type newType) { if (target == null || newType == null) { return; } BTEditorGraphNode parentNode = target.Parent; Vector2 oldPosition = target.NodePosition; int oldIndex = target.Parent.GetChildIndex(target); BehaviourNode node = BTUtils.CreateNode(newType); if (node != null) { node.Constraints.AddRange(target.Node.Constraints); if (node is Decorator) { Decorator original = target.Node as Decorator; Decorator decorator = node as Decorator; decorator.SetChild(original.GetChild()); } else if (node is Composite) { Composite original = target.Node as Composite; Composite composite = node as Composite; for (int i = 0; i < original.ChildCount; i++) { composite.AddChild(original.GetChild(i)); } } BTUndoSystem.BeginUndoGroup("Changed node type"); BTUndoSystem.RegisterUndo(new UndoNodeDeleted(target)); target.OnDelete(); BTEditorGraphNode newNode = parentNode.OnInsertChild(oldIndex, node); if (newNode != null) { newNode.NodePosition = oldPosition; BTUndoSystem.RegisterUndo(new UndoNodeCreated(newNode)); } BTUndoSystem.EndUndoGroup(); } }
private static Composite FromXml(XElement xml, Composite comp) { var pbComponentTypes = (from type in Assembly.GetExecutingAssembly().GetTypes() where (typeof(IPBComponent)).IsAssignableFrom(type) && !type.IsAbstract let eleAttr = type.GetCustomAttribute <PBXmlElementAttribute>() where eleAttr != null select new { Type = type, EleAttr = eleAttr }).ToArray(); foreach (XNode node in xml.Nodes()) { if (node.NodeType == XmlNodeType.Comment) { comp.AddChild(new CommentAction(((XComment)node).Value)); continue; } if (node.NodeType != XmlNodeType.Element) { continue; } var element = (XElement)node; var elementName = element.Name.ToString(); var typeInfo = pbComponentTypes.FirstOrDefault( t => (string.IsNullOrEmpty(t.EleAttr.Name) && t.Type.Name == elementName) || t.EleAttr.Matches(elementName)); if (typeInfo == null) { throw new InvalidOperationException(string.Format("Unable to bind XML Element: {0} to a Type", element.Name)); } var pbComp = (IPBComponent)Activator.CreateInstance(typeInfo.Type); pbComp.OnProfileLoad(element); var pbXmlAttrs = (from pi in typeInfo.Type.GetProperties() let attrAttr = pi.GetCustomAttribute <PBXmlAttributeAttribute>() where attrAttr != null select new { PropInfo = pi, AttrAttr = attrAttr }).ToList(); Dictionary <string, string> attributes = element.Attributes().ToDictionary(k => k.Name.ToString(), v => v.Value); // use legacy X,Y,Z location for backwards compatability if (attributes.ContainsKey("X")) { string location = string.Format("{0},{1},{2}", attributes["X"], attributes["Y"], attributes["Z"]); var prop = pbXmlAttrs.Where( p => (string.IsNullOrEmpty(p.AttrAttr.Name) && p.PropInfo.Name == "Location") || p.AttrAttr.Matches("Location")) .Select(p => p.PropInfo) .FirstOrDefault(); if (prop != null) { prop.SetValue(pbComp, location, null); attributes.Remove("X"); attributes.Remove("Y"); attributes.Remove("Z"); } } foreach (var attr in attributes) { var propInfo = pbXmlAttrs.Where( p => (string.IsNullOrEmpty(p.AttrAttr.Name) && p.PropInfo.Name == attr.Key) || p.AttrAttr.Matches(attr.Key)) .Select(p => p.PropInfo).FirstOrDefault(); if (propInfo == null) { PBLog.Log("{0}->{1} appears to be unused", elementName, attr.Key); continue; } // check if there is a type converter attached var typeConverterAttr = (TypeConverterAttribute)propInfo.GetCustomAttributes(typeof(TypeConverterAttribute), true).FirstOrDefault(); if (typeConverterAttr != null) { try { var typeConverter = (TypeConverter)Activator.CreateInstance(Type.GetType(typeConverterAttr.ConverterTypeName)); if (typeConverter.CanConvertFrom(typeof(string))) { propInfo.SetValue(pbComp, typeConverter.ConvertFrom(null, CultureInfo.InvariantCulture, attr.Value), null); } else { PBLog.Warn("The Type Converter {0} can not convert from string.", typeConverterAttr.ConverterTypeName); } } catch (Exception ex) { PBLog.Warn("Type conversion for {0} has failed.\n{1}", typeInfo.Type.Name + attr.Key, ex); } } else { propInfo.SetValue( pbComp, propInfo.PropertyType.IsEnum ? Enum.Parse(propInfo.PropertyType, attr.Value) : Convert.ChangeType(attr.Value, propInfo.PropertyType, CultureInfo.InvariantCulture), null); } } if (pbComp is Composite) { FromXml(element, pbComp as Composite); } comp.AddChild((Component)pbComp); } return(comp); }
static void Main(string[] args) { //Question 1 Context ctx = new Context(new ShipSafe(0)); ctx.LevelUp(); ctx.LevelUp(); ctx.TakeDamage(); ctx.LevelUp(); ctx.LevelUp(); ctx.LevelUp(); ctx.TakeDamage(); ctx.TakeDamage(); //Question 2 Component root = new Composite(2); Component circle1 = new Leaf(1); Component rectangle = new Leaf(2); root.AddChild(circle1); root.AddChild(rectangle); Component container1 = new Composite(1); Component circle2 = new Leaf(3); Component circle3 = new Leaf(1); container1.AddChild(circle2); container1.AddChild(circle3); root.AddChild(container1); Component container2 = new Composite(1); Component t1 = new Leaf(5); Component t2 = new Leaf(1); Component t3 = new Leaf(1); container2.AddChild(t1); container2.AddChild(t2); container2.AddChild(t3); root.AddChild(container2); root.Draw(""); Console.WriteLine(root.countLeaf()); //Console.WriteLine(container1.countLeaf()); //Console.WriteLine(container2.countLeaf()); //Console.WriteLine(t1.countLeaf()); Console.WriteLine(isZugi(root)); //Question 3 CarProxy car = new CarProxy(); // Drive the car car.StartDriving(); car.showLocation(); //Question 5 FatalLogger fatal = new FatalLogger(); ErrorLogger error = new ErrorLogger(); InfoLogger info = new InfoLogger(); LogBase chainRoot = fatal; fatal.SetNext(error); error.SetNext(info); info.SetNext(null); chainRoot.Log("tell me why", 2); Console.WriteLine("=================="); //Question 8 GymAccessObject gymthings = new GymBase(); gymthings.Run(); //Question 10 IWindow window = new BaseWindow(); IWindow Tlatmeimad = new TlatMeimadWindow(window); IWindow super = new FlashingWindow(Tlatmeimad); Console.WriteLine(super.GetDetails()); IWindow myfavoriteWindow = new Colors(new TlatMeimadWindow(new FlashingWindow(new BaseWindow()))); Console.WriteLine(myfavoriteWindow.GetDetails()); //Question 12 ComputerFactoryMethod cf = new ComputerFactoryMethod(); Computer v1 = cf.GetComputer("Gaming"); }