Now, let's implement the Observer pattern in a simple way that can be reused in various contexts:
- We are going to start this code example by implementing the two elements of the pattern. Let's begin with the Subject class:
using UnityEngine;
using System.Collections;
namespace Chapter.Observer
{
public abstract class Subject : MonoBehaviour
{
private readonly
ArrayList _observers = new ArrayList();
public void Attach(Observer observer)
{
_observers.Add(observer);
}
public void Detach(Observer observer)
{
_observers.Remove(observer);
}
public void NotifyObservers()
{
foreach (Observer observer in _observers)
{
observer.Notify(this);
}
}
}
}
The Subject abstract class has three methods. The first two, Attach() and Detach(), are responsible for adding or removing an observer object from...