1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef UTILS_BASE_OBSERVER_H 17 #define UTILS_BASE_OBSERVER_H 18 19 #include <memory> 20 #include <vector> 21 #include <set> 22 #include <mutex> 23 24 namespace OHOS { 25 26 27 struct ObserverArg { 28 public: 29 virtual ~ObserverArg() = default; 30 }; 31 32 class Observer; 33 class Observable { 34 public: 35 virtual ~Observable() = default; 36 void AddObserver(const std::shared_ptr<Observer>& o); 37 void RemoveObserver(const std::shared_ptr<Observer>& o); 38 void RemoveAllObservers(); 39 void NotifyObservers(); 40 void NotifyObservers(const ObserverArg* arg); 41 int GetObserversCount(); 42 43 protected: 44 bool HasChanged(); 45 void SetChanged(); 46 void ClearChanged(); 47 48 protected: 49 std::set<std::shared_ptr<Observer>> obs; 50 std::mutex mutex_; 51 52 private: 53 bool changed_ = false; 54 }; 55 56 class Observer { 57 public: 58 virtual ~Observer() = default; 59 virtual void Update(const Observable* o, const ObserverArg* arg) = 0; 60 }; 61 62 63 } 64 65 #endif 66 67