How should I implement observer pattern?

Delegate seems to be a good choice. And maybe we can use Interface to achieve Observer?

Can anyone share his/her experience about this please?

You can definitely use delegates for this. You won’t even need an interface for the observers.
For example, you have this in your first class:



class UBlah
{
    ...

    DECLARE_MULTICAST_DELEGATE(FBlahDelegate);
    FBlahDelegate OnSomethingChanged;

    void ChangeSomething()
    {
        // Do something important

        OnSomethingChanged.ExecuteIfBound();
    }
};


And you can easily bind a method in the observer to receive that delegate from a specific object:


Blah->OnSomethingChanged.BindUObject(this, &UWhatever::ReceiveSomethingChanged);

There’s a bunch of stuff here: Delegates | Unreal Engine Documentation

2 Likes