Register all GUI components as Observers or pass current object to next object as a constructor argu

Posted by Jack on Stack Overflow See other posts from Stack Overflow or by Jack
Published on 2010-03-18T05:55:22Z Indexed on 2010/03/18 6:01 UTC
Read the original article Hit count: 386

First, I'd like to say that I think this is a common issue and there may be a simple or common solution that I am unaware of. Many have probably encountered a similar problem. Thanks for reading.

I am creating a GUI where each component needs to communicate (or at least be updated) by multiple other components. Currently, I'm using a Singleton class to accomplish this goal. Each GUI component gets the instance of the singleton and registers itself. When updates need to be made, the singleton can call public methods in the registered class. I think this is similar to an Observer pattern, but the singleton has more control. Currently, the program is set up something like this:

class c1 {
    CommClass cc;
    c1() {
        cc = CommClass.getCommClass();
        cc.registerC1( this );
        C2 c2 = new c2();
    }
}

class c2 {
    CommClass cc;
    c2() {
        cc = CommClass.getCommClass();
        cc.registerC2( this );
        C3 c3 = new c3();
    }
}

class c3 {
    CommClass cc;
    c3() {
        cc = CommClass.getCommClass();
        cc.registerC3( this );
        C4 c4 = new c4();
    }
}

etc.

Unfortunately, the singleton class keeps growing larger as more communication is required between the components.

I was wondering if it's a good idea to instead of using this singleton, pass the higher order GUI components as arguments in the constructors of each GUI component:

class c1 {
    c1() {
        C2 c2 = new c2( this );
    }
}

class c2 {
    C1 c1;
    c2( C1 c1 ) {
        this.c1 = c1
        C3 c3 = new c3( c1, this );
    }
}

class c3 {
    C1 c1;
    C2 c2;
    c3( C1 c1, C2 c2 ) {
        this.c1 = c1;
        this.c2 = c2;
        C4 c4 = new c4( c1, c2, this );
    }
}

etc.

The second version relies less on the CommClass, but it's still very messy as the private member variables increase in number and the constructors grow in length.

Each class contains GUI components that need to communicate through CommClass, but I can't think of a good way to do it.

If this seems strange or horribly inefficient, please describe some method of communication between classes that will continue to work as the project grows. Also, if this doesn't make any sense to anyone, I'll try to give actual code snippets in the future and think of a better way to ask the question. Thanks.

© Stack Overflow or respective owner

Related posts about java

Related posts about design-patterns