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
VideoProcessingclass has a dependency on theImageProcessingclass, however, you only wish to make yourMainFormaware 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
EventAggregatoror aMediator. Both of these behavioural patterns are designed to decouple objects involved in the messaging process and provide apublish/subscribemechanism.As an example if you were to implement the
EventAggregatoryourMainFormwould be asubscriber, listening out for notifications sent from apublisherwhich in your scenario is theImageProcessingclass.A contrived code example might look like the following:
When the
ImageProcessingclasspublishesaNewBitmapEvent, only theMainFormis notified as only it, and not theVideoProcessingclass issubscribedto the event. Obviously if other classes were subscribed then they too would be notified when the event ispublished.