Alejander
Alejander

Reputation: 81

How to use the same instance of an object

I wonder if there is a simple way to use the same instance of an object in Java.

I have a MySerial class, used to communicate via serial (I'm using RXTX library, but it's not relevant to the problem).

Let's assume that:

I want that the same instance of MySerial used in the GUI is the same used in the Performer class. The problem is that Performer and GUI don't know each other: it's like they are two separated programs, so I can't just pass MySerial to constructors.

I tried playing around using SingleTon and ClassLoader, but none of it worked.

Any advice?

Upvotes: 0

Views: 186

Answers (3)

Paul Vargas
Paul Vargas

Reputation: 42030

If you have each instance in its own JVM (one java.exe in TaskManager in Windows), you can't share the same instance of MySerial. You need init in the same process the two applications. The you can use a enum o Singleton.

public class Main {
    enum MySerial { ... }
    public static void main(String... args) {
       Performer.main(args);
       GUI.main(args);
    }
}

Upvotes: 0

pfh
pfh

Reputation: 530

Even though Singleton pattern will solve your problem - it's not something you should use very often(avoid it at all cost). Why don't you simply send the reference to an object? If it's too difficult, you probably have some problems with the architecture. Fix the architecture - don't avoid the problem with singleton patterns or you'll find yourself in a lot of mess!

Upvotes: 2

MByD
MByD

Reputation: 137362

Seems like the singleton pattern is what you need. it's rather simple to implement and should not make a problem (according to what you describe) For example:

public class MySingleton {

    private static MySingleton instance;

    private MySingleton() {}

    public static MySingleton getInstance() {
        if (instance == null)
            instance = new MySingleton();
        return instance;
    }

    private String s = "hello";
    public String getString() {
        return s;
    }

}

From GUI / Performer:

String someString = MySingleton.getInstance().getString();

Upvotes: 0

Related Questions