Sync.h (1637B)
1 /* 2 ZynAddSubFX - a software synthesizer 3 4 Sync.h - allow sync callback using observer pattern 5 Copyright (C) 2024 Michael Kirchner 6 7 This program is free software; you can redistribute it and/or 8 modify it under the terms of the GNU General Public License 9 as published by the Free Software Foundation; either version 2 10 of the License, or (at your option) any later version. 11 */ 12 #pragma once 13 #include <algorithm> // for std::find 14 15 namespace zyn { 16 17 #define MAX_OBSERVERS 8 18 19 class Observer { 20 public: 21 virtual void update() = 0; 22 }; 23 24 25 class Sync { 26 public: 27 Sync() {observerCount = 0;} 28 void attach(Observer* observer) { 29 if (observerCount >= MAX_OBSERVERS) { 30 return; // No space left to attach a new observer 31 } 32 // Check if already attached 33 if (std::find(observers, observers + observerCount, observer) != observers + observerCount) { 34 return; // Observer already attached 35 } 36 observers[observerCount++] = observer; 37 } 38 void detach(const Observer* observer) { 39 // Find the observer 40 auto it = std::find(observers, observers + observerCount, observer); 41 if (it == observers + observerCount) { 42 return; // Observer not found 43 } 44 // Remove the observer by shifting the rest 45 std::move(it + 1, observers + observerCount, it); 46 --observerCount; 47 } 48 void notify() { 49 for (int i = 0; i < observerCount; ++i) { 50 observers[i]->update(); 51 } 52 } 53 54 private: 55 Observer* observers[MAX_OBSERVERS]; 56 int observerCount; // Current number of observers 57 }; 58 59 }