用C#观察者设计模式写 半夜老鼠进屋了,玻璃瓶碰倒打碎了,孩子吓哭了,妈去哄孩子,爸去开灯打老鼠
时间: 2024-10-09 17:13:48 浏览: 49
C# 设计模式系列教程-观察者模式
在C#中,观察者设计模式可以模拟上述场景。首先,我们需要创建三个角色:观察者(Subject)、目标状态改变的对象(Observer)以及具体的事件(Event)。在这个例子中:
1. 观察者(Subject) - 家庭成员的角色,如妈妈和爸爸。他们会作为订阅者监听特定事件。
```csharp
public abstract class FamilyMember : IObserver<Sound>
{
public void Update(Sound sound)
{
HandleSound(sound);
}
protected abstract void HandleSound(Sound sound);
}
```
2. 目标状态改变的对象(Observer) - 玻璃瓶,它会触发事件。
```csharp
public class GlassBottle : Subject
{
private bool isBroken;
public event Sound Changed;
// 模拟瓶子被打碎的动作
public void Break()
{
isBroken = true;
if (Changed != null)
Changed(this, new Sound("break"));
}
}
```
3. 事件 - 声音(Sound)。
```csharp
public enum Sound
{
MouseEnter,
GlassBreak,
ChildCries,
LightTurnedOn
}
```
4. 具体行为:孩子和父母处理声音的行为。
```csharp
public class Child : FamilyMember
{
public override void HandleSound(Sound sound)
{
switch (sound)
{
case Sound.ChildCries:
Console.WriteLine("孩子被吓哭了");
break;
default:
base.HandleSound(sound);
break;
}
}
}
public class Mother : FamilyMember
{
public override void HandleSound(Sound sound)
{
switch (sound)
{
case Sound.ChildCries:
Console.WriteLine("妈妈去哄孩子");
break;
case Sound.LightTurnedOn:
Console.WriteLine("妈妈发现黑,打开了灯");
break;
default:
base.HandleSound(sound);
break;
}
}
}
public class Father : FamilyMember
{
public override void HandleSound(Sound sound)
{
switch (sound)
{
case Sound.GlassBreak:
Console.WriteLine("爸爸听到声音,去开灯打老鼠");
break;
default:
base.HandleSound(sound);
break;
}
}
}
```
最后,在主程序里初始化并触发事件:
```csharp
public static void Main(string[] args)
{
var bottle = new GlassBottle();
var child = new Child();
var mother = new Mother();
var father = new Father();
bottle.Subscribe(child);
bottle.Subscribe(mother);
bottle.Subscribe(father);
// 模拟半夜老鼠进入
bottle.Changed += (_, e) => bottle.Break();
// ...其他逻辑,这里只演示触发事件
bottle.Changed(this, new Sound(MouseEnter));
}
```
阅读全文