我有3个名为Computer,Recorder和Controller的类。每个类只有一个实例。计算机和记录器类是边界类,并且具有指向控制器的定向关联。我已经在Computer的load方法中声明了Controller控件。我希望Recorder边界类指向我在计算机中声明的同一个控制器。如何在不破坏指导协会的情况下这样做?
所以我在计算机中声明:
Controller control = new Controller();
//Then passed in a lot of inputs from this boundary class to lists in controller.
我希望能够从Recorder类访问这些列表。 一次只能控制一个控制器实例(Singleton)。
如果我需要澄清,请告诉我。
至于为什么我这样做,我试图坚持高级程序员提供的类图。
谢谢!
答案 0 :(得分:1)
如果你真的只需要一个Controller类的实例,你可以考虑使用单例设计模式。这看起来像这样:
// 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);
由于构造函数是私有的,因此可以通过从类外部创建其他实例来搞乱。而且您不需要将任何关联保存到计算机和记录器类中的Controller类。