سؤال

I have 3 classes named Computer, Recorder, and Controller. There is only one instance of each class. The Computer and Recorder classes are boundary classes and have a directed association pointed to the controller. I have declared Controller control within the load method for Computer. I want the Recorder boundary class to point to the same controller I declared within computer. How would I do this without disrupting the directed associations?

So I declared within Computer:

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

I want to have access to these lists from the Recorder class. Only one instance of controller should be up at once(Singleton).

Please let me know if I need to clarify.

As for why I'm doing it this way, I'm trying to stick to a class diagram provided by a senior programmer.

Thanks!

هل كانت مفيدة؟

المحلول

If you really only need one instance of the Controller class you could think of using the singleton design pattern. This would look like this:

// 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
    }
}

So in your code you can simply access the single instance of Controller like this:

Controller.Instance.MyMethod(computer, recorder);

Since the constructor is private you can't mess by creating an additional instance from outside the class. And you don't need to save any associations to the Controller class inside Computer and Recorder classes.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top