当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知依赖它的对象。观察者模式属于行为型模式。
使用场景:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
举例:我们用猫抓老鼠的来举例子。当汤姆猫进屋子的时候,杰瑞用跑步的方式逃跑,米老鼠骑自行车逃跑,舒克开坦克逃跑。
这个时候汤姆猫就是被观察者,有一个进屋子的方法。杰瑞,米老鼠,舒克就是观察者都有一个逃跑的方法。
优点: 1、观察者和被观察者是抽象耦合的,使用委托在观察者中注册事件更能大大降低耦合。 2、建立一套触发机制。
被观察者,猫类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
/// <summary>
/// 猫
/// </summary>
public class Cat : MonoBehaviour
{
private string name;
private string color;
public event Action CatAction;
public Cat(string name,string color)
{
this.name = name;
this.color = color;
}
void Start()
{
}
public void CatIntoRoom()
{
Debug.Log("叫" + name + "的" + color + "猫,进屋了。");
CatAction?.Invoke();
}
}
老鼠抽象类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Mouse
{
protected string name;
public abstract void Run();
}
观察者
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 米老鼠
/// </summary>
public class Mickey : Mouse
{
public Mickey(string name,Cat cat)
{
this.name = name;
cat.CatAction += Run;
}
public override void Run()
{
Debug.Log(name + "骑自行车,逃跑了");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 杰瑞
/// </summary>
public class Jerry : Mouse
{
public Jerry(string name,Cat cat)
{
this.name = name;
cat.CatAction += Run;
}
public override void Run()
{
Debug.Log(name + "跑步,逃跑了");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 舒克
/// </summary>
public class Schuck : Mouse
{
public Schuck(string name, Cat cat)
{
this.name = name;
cat.CatAction += Run;
}
public override void Run()
{
Debug.Log(name + "开坦克,逃跑了");
}
}
调用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StartController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Cat cat = new Cat("汤姆", "蓝色");
Jerry jerry = new Jerry("杰瑞", cat);
Mickey mickey = new Mickey("米老鼠", cat);
Schuck schuck = new Schuck("舒克", cat);
cat.CatIntoRoom();
}
}