Is there a better solution to send data from one class to another through different class? I have image in class ImageProccessing and I would like to send him to class MainForm.
- MainForm.cs (GUI)
- VideoProccessing.cs
- ImageProccessing.cs
I have this pseudocode:
class MainForm : Form
{
VideoProccessing _video = new VideoProccessing();
}
class VideoProccessing
{
ImageProccessing _image = new ImageProccessing();
}
class ImageProccessing
{
Bitmap _bmp = null;
public void SomeBadassProcess()
{
_bmp = new Bitmap(); //How to send this to MainForm (GUI)
}
}
My solution:
class MainForm : Form
{
VideoProccessing _video = new VideoProccessing();
_video.SendAgain += (ShowImage);
private void ShowImage(Bitmap bmp)
{
SomePictureBox.Image = bmp;
}
}
class VideoProccessing
{
ImageProccessing _image = new ImageProccessing();
_image.Send += (ReceivedImage)
public delegate void SendAgainImage(Bitmap bmp);
public event SendAgainImage SendAgain;
private void ReceivedImage(Bitmap bmp)
{
SendAgain(bmp);
}
}
class ImageProccessing
{
Bitmap _bmp = null;
public delegate void SendImage(Bitmap bmp);
public event SendImage Send;
public void SomeBadassProcess()
{
_bmp = new Bitmap(); //How to send this to MainForm (GUI)
Send(_bmp);
}
}
If your
VideoProcessing
class has a dependency on theImageProcessing
class, however, you only wish to make yourMainForm
aware ofVideoProcessing
, then propagating your message in the manner that you are is probably acceptable. It does however create a strong coupling between your objects, which, you may or may not care about at this stage.Another method could be to use some sort of message bus such as an
EventAggregator
or aMediator
. Both of these behavioural patterns are designed to decouple objects involved in the messaging process and provide apublish/subscribe
mechanism.As an example if you were to implement the
EventAggregator
yourMainForm
would be asubscriber
, listening out for notifications sent from apublisher
which in your scenario is theImageProcessing
class.A contrived code example might look like the following:
When the
ImageProcessing
classpublishes
aNewBitmapEvent
, only theMainForm
is notified as only it, and not theVideoProcessing
class issubscribed
to the event. Obviously if other classes were subscribed then they too would be notified when the event ispublished
.