C# C语言中的边界和控制器类关联#
我有三门课,分别是计算机、录音机和控制器。每个类只有一个实例。计算机类和记录器类是边界类,具有指向控制器的定向关联。我已经在计算机的加载方法中声明了控制器控制。我希望记录器边界类指向我在计算机中声明的同一控制器。我如何在不破坏定向关联的情况下做到这一点 所以我在电脑里声明:C# C语言中的边界和控制器类关联#,c#,associations,C#,Associations,我有三门课,分别是计算机、录音机和控制器。每个类只有一个实例。计算机类和记录器类是边界类,具有指向控制器的定向关联。我已经在计算机的加载方法中声明了控制器控制。我希望记录器边界类指向我在计算机中声明的同一控制器。我如何在不破坏定向关联的情况下做到这一点 所以我在电脑里声明: Controller control = new Controller(); //Then passed in a lot of inputs from this boundary class to lists in con
Controller control = new Controller();
//Then passed in a lot of inputs from this boundary class to lists in controller.
我想从Recorder类访问这些列表。
一次只能启动控制器的一个实例(单实例)
如果我需要澄清,请告诉我
至于我为什么这样做,我试图坚持一个高级程序员提供的类图
谢谢 如果您真的只需要控制器类的一个实例,您可以考虑使用单例设计模式。这看起来像这样:
// 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.Instance.MyMethod(computer, recorder);
因此,在您的代码中,您可以简单地访问控制器的单个实例,如下所示:
// 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.Instance.MyMethod(computer, recorder);
由于构造函数是私有的,所以不能通过从类外部创建其他实例来搞乱它。您不需要在Computer和Recorder类中保存与Controller类的任何关联