1# Copyright 2023 Google LLC 2# 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# https://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"""Simple observer base class.""" 15 16import logging 17 18 19class ObserverBase: 20 """Simple observer base class that provides the observer pattern.""" 21 22 def __init__(self): 23 self.observers = {} 24 25 def add_observer(self, name, observer): 26 """Add named observer if it doesn't already exist. 27 28 Args: 29 name: 30 Unique name for the observer. 31 observer: 32 Object that implements the observer callbacks. 33 34 Returns: 35 True if observer was added. 36 """ 37 if name not in self.observers: 38 self.observers[name] = observer 39 return True 40 41 logging.warning('Observer {} already exists, not adding'.format(name)) 42 return False 43 44 def remove_observer(self, name, observer): 45 """Remove named observer.""" 46 if name in self.observers: 47 del self.observers[name] 48