C#中的边界和控制器类关联

本文关键字:控制器 关联 边界 | 更新日期: 2023-09-27 18:00:58

我有三个类,分别命名为Computer、Recorder和Controller。每个类只有一个实例。Computer和Recorder类是边界类,具有指向控制器的定向关联。我已经在计算机的加载方法中声明了控制器控制。我希望Recorder边界类指向我在计算机中声明的同一个控制器。我该如何在不破坏定向关联的情况下做到这一点?

所以我在计算机内部声明:

Controller control = new Controller();
//Then passed in a lot of inputs from this boundary class to lists in controller.

我想从Recorder类访问这些列表。一次只能启动一个控制器实例(Singleton(。

如果我需要澄清,请告诉我。

至于我为什么要这样做,我试图坚持一位资深程序员提供的类图。

谢谢!

C#中的边界和控制器类关联

如果您真的只需要Controller类的一个实例,您可以考虑使用singleton设计模式。这看起来像这样:

// Singleton
public class Controller
{
    // a Singleton has a private constructor
    private Controller()
    {
    }
    // this is the reference to the single instance
    private static Controller _Instance;
    // this is the static property to access the single instance
    public static Controller Instance
    {
        get
        {
            // if there is no instance then we create one here
            if (_Instance == null)
                _Instance = new Controller();
            return _Instance;
        }
    }
    public void MyMethod(Computer computer, Recorder recoder)
    {
        // Do something here
    }
}

因此,在您的代码中,您可以简单地访问Controller的单个实例,如下所示:

Controller.Instance.MyMethod(computer, recorder);

由于构造函数是私有的,所以不能通过从类外部创建额外的实例来搞砸。并且您不需要在Computer和Recorder类中保存与Controller类的任何关联。