dimanche 23 octobre 2022

C# class pattern sending messages back up chain

this is probably a fairly noob question - I'm not sure what the correct way to perform the below is, this occurs quite often in my code and there must be a "proper" solution / pattern to solve this. Consider the following:-

    class First
        {
            Second second = new Second();
            public void talkToSomethingExternal()
            {
                second.secondEvent(); // At some point I've decided I want to fire an event down the chain
            }
            public void sendMessage(string message)
            {
    
            }
    
    
        }
    
        class Second
        {
            Third third = new Third();
            public void secondEvent()
            {
                third.thirdEvent();
            }
        }
    
        class Third
        {
            public void thirdEvent()
            {
                // I want the first class to send a message, sendMessage("Message")
            }
        }

The method I normally end up taking is as below, passing a reference to the top class:-

 class First
    {
        Second second;

        public First ()
        {
            second = new Second(this);
        }
        public void talkToSomethingExternal()
        {
            second.secondEvent(); // At some point i've decided i want to fire an event down the chain
        }
        public void sendMessage(string message)
        {

        }


    }

    class Second
    {
        Third third; 

        public Second(First first)
        {
            third = new Third(first);
        }
        public void secondEvent()
        {
            third.thirdEvent();
        }
    }

    class Third
    {
        First storeFirst;

        public Third(First first)
        {
            storeFirst = first;
        }
        public void thirdEvent()
        {
            storeFirst.sendMessage("Message");
        }
    }

I could also just use a return type from the event, however again the messages are being passed from class to class back up the "chain" and also if any return value is required from sendMessage(..) this would be difficult and even more convoluted to achieve.

It seems a messy way to do this. I am also not aware of seeing this behaviour in the various frameworks (take WinForms as an example), so is there a different way of approaching this? I'm also finding it difficult to ascertain what this problem is actually called.

Thanks

Aucun commentaire:

Enregistrer un commentaire