I'm currently struggling with implementing a set of file system classes. I suppose this requires a composite diagram if I am not mistaken. Therefore, I created the following classes:
An abstract Node class that has a link to its parent folder and two Folder and File classes that implement Node . A folder contains a collection of all its children and methods for adding and removing children.
The fact is that I canβt understand how to correctly implement all the methods. In all the examples that I saw, children do not have a reference to the parent. How does the AddChild method ensure that the parent link of the child is set correctly? I decided that by checking if child.Parent already installed in the folder or child.Parent ArgumentException . The matter is complicated by the fact that AddChild can also throw an exception like DuplicateNameException or something else. So my methods look like this:
File.AddTo(Folder folder) { this.Parent = folder; try { folder.AddChild(this); } catch { this.Parent = null; throw; } } Folder.AddChild(Node child) { if(child.Parent != this) throw new ArgumentException(...); ... }
Now I have this ugly AddTo method and can't do something like someFolder.AddChild(new File(...)) . I wonder how this was implemented using ListViewItem , for example. There I can just do someListView.Items.Add(new ListViewItem(...)) .
My solution works, but I'm not sure if this is the right way to do this. Maybe someone has a better solution or can point to a good example. Thanks in advance.
EDIT . The following are the minimum complete class definitions.
abstract class Node { public Folder Parent { get; protected set; } public string Name { get; private set; } public Node(string name) { Parent = null; Name = name; } } class Folder : Node { private Dictionary<string, Node> _children; public Folder(string name) : base(name) {
source share