多个实例相同的上下文(无法控制构造函数)API

时间:2017-04-09 01:12:24

标签: c# .net-core

我正在尝试设计我的第一个API,到目前为止它看起来很酷但是我在过去几天碰到了一堵砖墙。

我无法控制我通过API提供的继承构造函数,而且我有一个类,在某些情况下需要从一开始就在多个实例之间共享。

我试图避免单身或静态属性,它们看起来不够干净。

并且

代码示例:

public abstract class Abstract
{
    private Context context;

    private IList<Abstract> sons;

    public Abstract
    {
        if(context == null)
           context = new Context();
    }

    //this part is where it gets problematic
    internal void AddContext(Context context)
    {
        this.context = context;
    }

    public void AddSon(Abstract abstract)
    {
        abstract.AddContext(this.context);
        sons.Add(abstract);
    }   
}

现在,用户将使用Abstract继承他/她的需求

public class Concrete : Abstract....

并根据自己的判断进行初始化

var concrete = new Concrete();
concrete.AddSon(new Concrete());

无需担心添加类似

的内容
concrete.AddSon(new Concrete(/*same context*/)

如果Concrete是son,那么Context应该被共享,否则不会。但是上下文应该在构造函数级别定义。

我希望我足够明确。提前谢谢。

0 个答案:

没有答案