jeudi 26 mars 2020

Parent Child Relation with restricted method access

Let's assume I have the following interfaces:

public interface IChild
{
    IParent MyParent { get; }
    string Name { get; set; }
}

public interface IParent : IChild
{
    IEnumerable<IChild> Children { get; }
}

In addition for the parent implementation there is the following abstract class:

public abstract class Parent : IParent
{
    private List<IChild> _children = new List<IChild>();

    public Parent(IParent parent, string name)
    {
        Name = name;
        MyParent = parent;
    }

    public IEnumerable<IChild> Children => _children;
    public IParent MyParent { get; }
    public string Name { get; set; }

    protected void Add(IChild child)
    {
        _children.Add(child);
    }
    protected void Remove(IChild child)
    {
        _children.Remove(child);
    }
}

Now I use the following implementation based on the interfaces and abstract class above:

public class Tree : Parent
{
    private Branch _left;
    private Branch _right;
    private Leaf _goldenLeaf;

    public Tree(IParent parent, string name) :
        base(parent, name)
    {
        _left = new Branch(this, "left branch");
        Add(_left);
        _right = new Branch(this, "left branch");
        Add(_right);
        _goldenLeaf = new Leaf(this, "the golden leaf");
        Add(_goldenLeaf);
    }
}

public class Branch : Parent
{
    private Leaf _singleLeaf;

    public Branch(IParent parent, string name) :
        base(parent, name)
    {
        _singleLeaf = new Leaf(this, "the golden leaf");
        Add(_singleLeaf);
    }
}

public class Leaf : IChild
{
    public Leaf(IParent parent, string name)
    {
        MyParent = parent;
        Name = name;
    }

    public IParent MyParent { get; }

    public string Name { get; set; }

    public void DoSomething()
    {
        // How can I have a method in the parent which can only be called
        // by the corresponding child. How to prevent the outside to call
        // the method "Inform" on the parent?
        MyParent.AskBeforeExecute(this, "data");
    }
}

The main problem I have is that I want to call a method from the parent within the "DoSomething" call which is only accessible by the children. So the "AskBeforeExecute" method can not be in the public interface of the IParent definition because then the "outer" world can also call this method. I am not sure if my idea can be implemented at all with interface as I have right now. Anyway I am stuck a little bit and I am looking for a better pattern or idea to handle this?

Aucun commentaire:

Enregistrer un commentaire