Предположим, у меня есть следующие интерфейсы:
public interface IChild
{
IParent MyParent { get; }
string Name { get; set; }
}
public interface IParent : IChild
{
IEnumerable<IChild> Children { get; }
}
В дополнение к родительской реализации есть следующий абстрактный класс:
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);
}
}
Теперь я использую следующую реализацию, основанную на интерфейсы и абстрактный класс выше:
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");
}
}
Основная проблема, с которой я столкнулся, заключается в том, что я хочу вызвать метод из родительского объекта в рамках вызова DoSomething, который доступен только дочерним элементам. Таким образом, метод "AskBeforeExecute" не может быть в интерфейсе publi c определения IParent, потому что тогда "внешний" мир также может вызывать этот метод. Я не уверен, что моя идея может быть реализована вообще с помощью интерфейса, как у меня сейчас. В любом случае, я немного застрял и ищу лучший шаблон или идею, чтобы справиться с этим?