简体   繁体   中英

How can I communicate between multiple classes?

I have three classes. For example's sake, I'll call them AwesomeClass, CoolClass, PrettyClass. AwesomeClass instantiates an object of CoolClass and PrettyClass. Now, I want CoolClass to change a variable inside PrettyClass.

What is the best way to go about this? One way that I can think of would be to send the reference of PrettyClass to CoolClass, and then CoolClass could do something like instanceOfPrettyClass.setSomeVariable("42"); . Or I could treat AwesomeClass as a controller and the other two classes as views (which is what they're being used as) and have CoolClass call some method in AwesomeClass which then calls another method in PrettyClass, but that feels very messy.

EDIT some example code

public class AwesomeClass
{
    public AwesomeClass()
    {
        CoolClass coolClass = new CoolClass();
        PrettyClass prettyClass = new PrettyClass();
    }
}

public class CoolClass
{
    public CoolClass()
    {
        Color colour = Color.RED;
    }
}

public class PrettyClass
{
    public PrettyClass()
    {
        //I want to set coolClass's colour to Color.BLACK here
    }
}

I'm surprised no one has answered this. I think you have the right idea, although it might be backwards.

public class AwesomeClass
{
    public AwesomeClass()
    {
        CoolClass coolClass = new CoolClass();
        PrettyClass prettyClass = new PrettyClass( coolClass );  // change
    }
}

public class CoolClass()
{
    private Color colour;  // change

    public CoolClass
    {
        colour = Color.RED;  // change
    }

    public void setColor( Color color ) {  // add setter
      colour = color;
    }
}

public class PrettyClass
{

    public PrettyClass( CoolClass cc )  // change
    {
        //I want to set coolClass's colour to Color.BLACK here
        cc.setColor( Color.BLACK );  // change
    }
}

I think that's it.

You can do it using constructors:

public class CalledClassA {
        public void doCalledClassA() {..} 
}

public class CalledClassB {
   private CalledClassA calledClassA;
   public CalledClassB(CalledClassA calledClassA) {
      this.calledClassA = calledClassA;
   }

   public void doSomething() {
      calledClassA.doCalledClassA();
   }
}

or using setters as suggested above. I prefer using contractors as possible from the following reasons: REPEAT AFTER ME: SETTER INJECTION IS A SYMPTOM OF DESIGN PROBLEMS

Can we claim a static method "set" in CoolClass ? We don't need to pass a reference as parameter in "PrettyClass" constructor in that case. Any time we want to change the color, just use CoolClass.set(...) to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM