有没有更好的解决方案通过不同的类将数据从一个类发送到另一个类?我在ImageProccessing课上有图像,我想把他送到MainForm课程。
我有这个伪代码:
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)
}
}
我的解决方案:
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);
}
}
答案 0 :(得分:1)
但是,如果您的VideoProcessing
课程依赖于ImageProcessing
课程,您只希望MainForm
知道VideoProcessing
,然后在你的态度可能是可以接受的。然而,它确实会在您的对象之间产生强烈耦合,在此阶段您可能会或可能不会关心它。
另一种方法可能是使用某种消息总线,例如EventAggregator
或Mediator
。这两种行为模式都旨在解耦消息传递过程中涉及的对象,并提供publish/subscribe
机制。
例如,如果您要实施EventAggregator
,MainForm
将是subscriber
,请聆听从您的方案中publisher
发送的通知ImageProcessing
上课。
一个人为的代码示例可能如下所示:
public class MainForm : Form
{
private readonly EventAggregator eventAggregator;
private readonly VideoProcessing videoProcessing;
public MainForm()
{
this.eventAggregator = new EventAggregator();
this.eventAggregator.Subscribe<NewBitmapEvent>(HandleNewBitMap);
this.videoProcessing = new VideoProcessing(this.eventAggregator);
}
private void HandleNewBitmap(Bitmap args)
{
// Do something
}
}
public class VideoProcessing
{
private readonly EventAggregator eventAggregator;
private readonly ImageProcessing imageProcessing;
public VideoProcessing(EventAggregator eventAggregator)
{
this.eventAggregator = eventAggregator;
this.imageProcessing = new ImageProcessing(this.eventAggregator);
}
}
public class ImageProcessing
{
private readonly EventAggregator eventAggregator;
public ImageProcessing(EventAggregator eventAggregator)
{
this.eventAggregator = eventAggregator;
this.eventAggregator.Publish<NewBitmapEvent>(new Bitmap(...));
}
}
当ImageProcessing
班publishes
和NewBitmapEvent
时,只有MainForm
会被通知,而VideoProcessing
班级不是subscribed
对事件。显然,如果订阅了其他类,那么当事件为published
时,他们也会收到通知。