如何让一个对象订阅另一个对象的事件,同时保持两者松散耦合?
我有以下代码,在我看来,它们似乎是实现观察者模式所需的基本基础知识。这是标准,还是我做错了什么?
public class LayoutManager
{
public CormantTimer Timer { get; set; }
}
protected void Page_Init(object sender, EventArgs e)
{
LayoutManager.Instance.Timer = RefreshAndCycleTimer;
}
public class CormantRadDock : RadDock, ICormantControl<RadDockSetting>
{
public CormantRadDock()
{
LayoutManager.Instance.Timer.TimerEvent += DoTimerRefreshTick;
}
}
CormantRadDock 对象是动态创建的。 RefreshAndCycleTimer 位于页面上。
我担心,随着我的项目变得越来越大,LayoutManager 中将会有大量不相关的控件——只是需要订阅。这是标准吗?我应该做一些不同的事情吗?
谢谢
I have the following bits of code which, in my mind, seem like the bare basics necessary to implement the Observer pattern. Is this standard, or am I doing something wrong?
public class LayoutManager
{
public CormantTimer Timer { get; set; }
}
protected void Page_Init(object sender, EventArgs e)
{
LayoutManager.Instance.Timer = RefreshAndCycleTimer;
}
public class CormantRadDock : RadDock, ICormantControl<RadDockSetting>
{
public CormantRadDock()
{
LayoutManager.Instance.Timer.TimerEvent += DoTimerRefreshTick;
}
}
The CormantRadDock objects are dynamically created. RefreshAndCycleTimer is on Page.
I am worried that, as my project grows larger, there will be a large amount of non-related controls in LayoutManager -- just there to be subscribed to. Is this standard? Should I be doing something different?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想要松散耦合的消息传递,请不要使用事件,请使用 EventAggragator。 Caliburn.Micro 有一个不错的。
http://devlicio.us/blogs/rob_eisenberg/archive/2011/05/30/caliburn-micro-soup-to-nuts-part-8-the-eventaggregator.aspx
EventAggregator 是一种中介者类型模式,允许发布者和订阅者通过中介进行工作,从而实现松散耦合的交互。发布者和订阅者不需要互相了解。
寻找使用“弱引用”的 EventAggregator 来克服事件类型模式的经典问题,即 GC 内存泄漏。 Caliburn 正是这样做的。
Don't use events if you want loosely-coupled messaging, use an EventAggragator. Caliburn.Micro has an decent one.
http://devlicio.us/blogs/rob_eisenberg/archive/2011/05/30/caliburn-micro-soup-to-nuts-part-8-the-eventaggregator.aspx
An EventAggregator is a Mediator type pattern that lets publishers and subscribers work through an intermediary, therefore enabling loosely-coupled interaction. Publishers and subscribers do not need to know about each other.
Look for an EventAggregator that uses "Weak Refereneces" to overcome the classic issue with eventing type patterns i.e. GC memory leaks. Caliburn does exactly this.
使用松散耦合的事件机制,例如
EventAggregator
http://msdn.microsoft.com/en-us/library/ff921122(PandP.20).aspx
Use a loosely-coupled eventing mechanism, like the
EventAggregator
http://msdn.microsoft.com/en-us/library/ff921122(PandP.20).aspx