从调用者类调用方法并避免循环依赖

时间:2014-03-25 02:32:45

标签: c# class design-patterns .net-assembly circular-dependency

我有一个Windows窗体应用程序包含3个项目的1个解决方案。

Hall.Client< - Winforms

Hall.Admin< - Winforms

Hall.Processor< - 类库

Hall.ClientHall.Admin需要Hall.Processor作为参考。由于循环依赖性,Hall.Processor无法添加对Hall.ClientHall.Admin的引用。 我只需要在Hall.Processor

中获取每个调用者类的实例

Hall.Client我有一个名为Canopy的课程

public class Canopy : System.Windows.Form
{
    public void SetProcessName(string name)
    {
        this.txtProcessName.Text = name;
    }
}

Hall.Admin我有一个名为Roof

的课程
public class Roof : System.Windows.Form
{
    public void SetProcessName(string name)
    {
        this.txtProcessName.Text = name;
    }
}

我在Builder类的Hall.Processor中有一个方法

public class Builder
{
    Form form;
    public Builder(Form form)
    {
        //Here the main problem.
        //if the caller class is Hall.Admin.Roof then this.form should be Hall.Admin.Roof
        //if the caller class is Hall.Client.Canopy then this.form should be Hall.Client.Canopy
    }
    public void SetProcessName()
    {
        //How to call method in caller class directly from this class
        //if(Admin.Roof) then form.SetProcessName("something about admin");
        //if(Client.Canopy) then form.SetProcessName("something about client");
    }
}

我需要建议如何解决我的问题。有没有与我的问题相关的设计模式?

1 个答案:

答案 0 :(得分:2)

通过使用接口将类彼此去耦。您可以在Processor库中声明所有接口,或者更好地在单独的库中声明,在ClientAdminProcessor项目之间共享。然后,您可以执行form is IRoofform is ICanopy等检查。

但请注意,在这种情况下,不会阻止Admin执行ICanopyClient执行IRoof。如果这确实是一个问题,请创建接口internal,并通过[assembly: InternalsVisibleTo("Assembly")]控制其对其他程序集的可见性(请参阅"Friend Assemblies")。

此外,在网上搜索"依赖注入"