如何解耦Observable和Observer之间的关系 [英] how to decouple the relationship between Observable and Observer
问题描述
您好,
以下代码来自 Tiny-0601 。
public delegate void mcEventHandler();
class Cat
{
string cName;
public event mcEventHandler CatCryEvent;
public Cat(string name)
{
cName = name;
}
public void Cry()
{
Console.WriteLine(cName+"coming");
Console.ReadLine();
CatCryEvent();
}
}
class Mouse
{
public string mName;
public Mouse(Cat cat)
{
cat.CatCryEvent += Run;
cat.CatCryEvent += new mcEventHandler(See);
}
private void Run()
{
Console.WriteLine("Cat is coming,"+mName+"I will be on my way");
}
private void See()
{
Console.WriteLine("See if the cat is still in");
Console.ReadLine();
}
}
class Program
{
static void Main(string[] args)
{
Cat cat1 = new Cat("Tom");
Mouse m1 = new Mouse(cat1);
cat1.Cry();
}
}
我想知道如何在Class Mouse中建立关系,而不是在Main方法中。 我想打电话给"cat1.Cry();"使用Event提升Mouse.Run()和Mouse.See(),而不使用"Mouse m1 = new Mouse(cat1)"。
I want to know how to build the relationship in Class Mouse, not in the Main method. I want to just call the "cat1.Cry();" to raise the Mouse.Run() and Mouse.See() by using Event, without using "Mouse m1 = new Mouse(cat1)".
谢谢。
Thank you.
推荐答案
虽然你可以这样做,但用例是什么?因此它不再是观察者模式。还要记住,你需要 类似于动作的寄存器类型。在鼠标类中执行此操作时,这意味着向鼠标类添加耦合,这会适得其反。
While you can do this, what is the use-case? Cause then it is no longer the observer pattern. Also keep in mind, you need a register type like action. When doing this in the mouse class, this means adding coupling to the mouse class, which is counterproductive.
这篇关于如何解耦Observable和Observer之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!