-1

I split my program according to the Model-View-Controller pattern so far. For my threads I created a new class:

public class MyThreadClass extends Thread 
{
    public MyThreadClass()
    {

    }

    public void run() 
    {
        //Call method from other class (public class Controller)
    }

}

In run()-method the thread shall call a method of another class, (e.g., public class Controller for my purpose).

I could instantiate the class controller but wouldn't that destroy the purpose of keeping to the MVC-principle?

How should I do that?

Shawn Mehan
  • 4,513
  • 9
  • 31
  • 51
freeprogramer233
  • 193
  • 2
  • 11

1 Answers1

1

Well, since you haven't given much detail, please be patient with an answer that might not match your problem exactly.

Also, the way you're structuring and asking this question makes me uneasy about your use of threads. I think you should reconsider whether or not you need threads for what you're doing.

But, to the point of answering... I'll give you two broad patterns to use while trying to call this Controller class method.

  1. Give your thread a reference to your Controller when you create it.

    public class MyThreadClass extends Thread 
    {
        private Controller controller;
    
        public MyThreadClass(Controller controller)
        {
            this.controller = controller;
        }
    
    public void run() 
    {
        //Call method from other class (public class Controller)
        controller.someMethod();
    }
    
  2. Make the controller's method public and static (If you don't know how to do that, then don't try using this approach -- declaring something static has greater complexities/assumptions than you want to mess with if you're already having problems with method accessability.) Then call it like this:

    public void run()
    {
         Controller.someMethod();
    }
    

And for your question about MVC:

I could instantiate the class controller but wouldn't that destroy the purpose of keeping to MVC-principle?

MVC requires that the View can connect to the Controller or communicate with it somehow. Instantiating a Controller generally has no effect on whether or not your design pattern is MVC. That being said, if you were asking about having each MyThreadClass instantiate its own version of the Controller... that would be poor MVC. Don't do that.

Jeutnarg
  • 1,138
  • 1
  • 16
  • 28